Problem with java.util.Map recordset

I had a strange problem with the following code.

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

and the code below does not compile.

 Map map = new HashMap(); for(Entry entry : map.entrySet()) { // compile error here // } 

Any clues?

+7
source share
2 answers

Bert has the right reason, and Henning expands it in the comments. When accessing a member of an unprocessed type, generics do not enter the game at all , even generics that do not rely on the type parameter.

As an example, this should compile just fine ...

 public class DataHolder<T> { public List<T> ts; public List<String> strings = new ArrayList<String>(); } //... DataHolder holder = new DataHolder(); holder.strings.add(Integer.valueOf(42)); 

... even if T does not need to be matched to a particular type to find out what the strings type should be.

This is true for universal member methods, what are you working for. entrySet returns the raw type of Set , not Set<Entry> , even if type parameters do not need to return Set<Entry> . The behavior is documented in the Java Language Specification, Section 4.8 :

The type of constructor (ยง8.8), the instance method (ยง8.8, ยง9.4) or the non-static field (ยง8.3) M of the raw type C that is not inherited from its superclasses or superinterfaces is the erasure of its type in the general declaration corresponding to C. The type of static a member of raw type C is the same as its type in the general declaration corresponding to C.

This is the gotcha rule.

see also

General Generations and General Arguments of the Java Class

+5
source

The signature of the entrySet method entrySet Set<Map.Entry<K, V>> entrySet() , so you can only refer to Map.Entry if you declared common types in the declaration, as it was in the first example. In the second, you use raw types, so essentially Set<Object> entrySet() , and you need a cast for it to work, for example.

 final Map map = new HashMap(); for(final Entry entry : (Set<Entry>)map.entrySet()) { // } 
+6
source

All Articles