tags:

views:

63

answers:

3

Hi all,

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.

A: 

Why doesn't this work ?

It depends on your compiler.

With javac 1.6.0_20 on a Mac, I didn't have any problem.

Maybe as @newacct suggested, generics were turned of for your extended for statement. But as it depends on your compiler (and not the JLS) it's not really easy to know why exactly.

How can this can be change to work ?

Map.Entry is a generic class, so if you choose to have generics in your application, you should use them everywhere.

Map<Object,Object> map=new HashMap<Object,Object>();
for (Map.Entry<Object, Object> entry:map.entrySet()){

}
Colin Hebert
You're avoiding the question. Why the compile error?
aioobe
@aioobe, updated, in fact it compiles on some compilers (here javac), without even a warning.
Colin Hebert
+5  A: 

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.

newacct
Great answer newacct. This one should be accepted.
aioobe
A: 

Prior to JDK1.5 map.entrySet() returned a Set (of Map.Entry, but you couldn't tell directly).

Set entries = map.entrySet();
Map.Entry entry = (Map.Entry) entries.iterator().next();  // <-- notice the cast!
Bivas