I wanted to create a variable I can iterate and sort later containing a "Move" and a double value. I thought my best shot would be the SortedMap with an integer (I read I need some kind of comparator) and an Entry containing my actual data. I have this method
public SortedMap<Integer, Entry<Move, Double>> listFishMoves(Field fishField) {
ArrayList<Move> fishMoves = getFishMoves(fishField);
SortedMap<Integer, SimpleEntry<Move, Double>> moveMap = new SortedMap<Integer, SimpleEntry<Move, Double>>();
int i = 0;
for (Move move : fishMoves) {
double turnValue = getMoveValue(move);
moveMap.put(i, new SimpleEntry(move, turnValue));
i++;
}
}
My Problem is that I get an error in line 3 when initializing the SortedMap (Cannot instantiate the type SortedMap>). I also get 2 warnings when adding the new SimpleEntry: 1. Type safety: The expression of type AbstractMap.SimpleEntry needs unchecked conversion to conform to AbstractMap.SimpleEntry 2. Description Resource Path Location Type Type safety: The expression of type AbstractMap.SimpleEntry needs unchecked conversion to conform to AbstractMap.SimpleEntry
I am totally new to Maps and would really appreciate your help!
Your problem is that SortedMap
is an interface - you cannot instantiate it. You need to select an implementation that suits your need.
For instance, you could use a TreeMap
.
SortedMap<Integer, SimpleEntry<Move, Double>> moveMap = new TreeMap<>();
For the warning, change your line to
moveMap.put(i, new SimpleEntry<>(move, turnValue));
Look for the words “interface”, “class”, and “implementing” when reading the JavaDoc.