zjffdu
zjffdu

Reputation: 28794

Compiler complains when I iterate Non-Generics Map in Java

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.

Upvotes: 6

Views: 4753

Answers (3)

Bivas
Bivas

Reputation: 1494

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!

Upvotes: 0

Colin Hebert
Colin Hebert

Reputation: 93167

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

}

Upvotes: -1

newacct
newacct

Reputation: 122439

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.

Upvotes: 7

Related Questions