3

This error appears when i try to loop my hashmap, and i have no idea why.

Object cannot be converted to Entry

Into package1:

protected static final Map<String, Integer> distanceLabels = new HashMap<>();

Into the package im having the error:

Map distanceLabels = package1.distanceLabels;
for (Map.Entry<String, Integer> entry : distanceLabels.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
GGirotto
  • 848
  • 2
  • 10
  • 31

2 Answers2

10

Simply replace this:

Map distanceLabels = package1.distanceLabels;

With this

Map<String, Integer> distanceLabels = package1.distanceLabels;

Indeed if you don't specify any parameterized types to the declaration of your map, the compiler cannot know the parameterized types of the entries which is the reason why he raises an error since you expect entries of specific types.

You need to remain consistent in both places such that you have actually 2 ways to fix it, you cannot do something in between as you did above:

  1. You can specify explicitly the parametrized types in both places like proposed above which is clearly the best approach
  2. You can create a raw type of Map as you did (no parameterized types defined) and create a raw type of Map.Entry but you will then have to explicitly cast your key and your value to the expected types.
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
1

Try to use the map Map<String, Integer> like this:

  Map<String, Integer> distanceLabels = package1.distanceLabels;
 for(Entry<String, Integer> entry : distanceLabels.entrySet()) {
   String key = entry.getKey();
   Object value = entry.getValue();

  }
Abdelhak
  • 8,299
  • 4
  • 22
  • 36