I am trying to use the firstKey() method for my treemap (memory). My code looks like:

import java.util.*;

//Code in the middle.

System.out.println(memory.firstKey());

It however gives me this error:

GameLogic.java:276: cannot find symbol
symbol  : method firstKey()
location: interface java.util.Map<java.lang.Integer,java.lang.Character>
System.out.println(memory.firstKey());
                                     ^

All advice appreciated. The same error happens if I use lastKey() as well.

有帮助吗?

解决方案

I think you have declared

Map map = new TreeMap();

you need to instead do

TreeMap map = new TreeMap(); //OR SortedMap map = new TreeMap() 
map.firstKey();

Because firstKey() is a method which exists in TreeMap which is not defined in Map contract (or interface)

其他提示

firstKey method is not defined in Map interface so map#firstKey creates compilation error. This method is defined in SortedMap.

Recommended would be -

SortedMap smap = ...; 
smap.firstKey();

or else

System.out.println((SortedMap)memory.firstKey());

or

System.out.println((TreeMap)memory.firstKey());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top