Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object cannot be converted to Entry<String,Integer> [duplicate]

Tags:

java

hashmap

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();
    // ...
}
like image 811
GGirotto Avatar asked Jul 22 '26 00:07

GGirotto


2 Answers

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.
like image 57
Nicolas Filotto Avatar answered Jul 23 '26 13:07

Nicolas Filotto


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();

  }
like image 25
Abdelhak Avatar answered Jul 23 '26 13:07

Abdelhak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!