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 wh开发者_运维技巧at's the reason ? Thanks in advance.
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.
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!
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()){
}
精彩评论