I’m having a strange problem with the following code works.
Map<String, Object> map = new HashMap<String, Object>();
for(Entry<String, Object> entry : map.entrySet()) {
//
}
while the code below does not compile.
Map map = new HashMap();
for(Entry entry : map.entrySet()) { // compile error here
//
}
Any clues?
Burt has the right reason and Henning expands on it in the comments. When referencing a member of a raw type, generics don’t come into play at all, even generics that don’t rely on the type parameter.
As an example, this should compile just fine…
…even though
Tdoesn’t need to be mapped to a concrete type to know what the type ofstringsshould be.This is true for generic member methods as well, which is what you are running into.
entrySetreturns the raw typeSet, notSet<Entry>, even though the type parameters would not need to be known to return aSet<Entry>. The behaviour is documented in the Java Language Specification, section 4.8:It’s a very “gotcha” rule.
See also
Java Class Generics and Method Generics conflicts