Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler complains when I iterate Non-Generics Map in Java

Tags:

java

generics

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.

like image 292
zjffdu Avatar asked Oct 11 '10 07:10

zjffdu


People also ask

Can HashMap be iterated?

In Java HashMap, we can iterate through its keys, values, and key/value mappings.

Why are raw types bad in Java?

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.

How many ways can you iterate a map in Java?

There are generally five ways of iterating over a Map in Java.

Are generics useful 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.


1 Answers

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 Objects out of it.

like image 167
newacct Avatar answered Sep 27 '22 18:09

newacct