I meet weired problem when I iterate a Non-Generics Map in Java
Map map=new HashMap();
for (Map.Entry entry:map.entrySet()){
}
But compiler complains and says that "Type mismatch: cannot convert from element type Object to Map.Entry" When I change the Map type to Generics, it can work
Map<Object,Object> map=new HashMap<Object,Object>();
for (Map.Entry entry:map.entrySet()){
}
It makes me confused, anybody know what's the reason ? Thanks in advance.
In Java HashMap, we can iterate through its keys, values, and key/value mappings.
The warning shows that raw types bypass generic type checks, deferring the catch of unsafe code to runtime. Therefore, you should avoid using raw types. The Type Erasure section has more information on how the Java compiler uses raw types.
There are generally five ways of iterating over a Map in Java.
Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.
When you use a raw type, like you do here with Map
, all generics is turned off, so entrySet()
just returns a bare Set
type (not Set<Map.Entry whatever>
), which, if you iterate over it, you can only get Object
s out of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With