I usually type my map declarations but was doing some maint and found one without typing. This got me thinking (Oh No!). What is the default typing of a Map declaration. Consider the following:
Map map = new HashMap(); map.put('one', '1st'); map.put('two', new Integer(2)); map.put('three', '3rd'); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + ' -> ' + entry.getValue()); }
this errors with a incompatible types on Map.Entry. So if I type the declaration with:
Map<Object, Object> map = new HashMap();
then all works well. So what is the default type that gets set in the declaration about? Or am I missing something else?
The type is java.lang.Object.
The for construct takes a type of Iterable and calls its iterator method. Since the Set isn’t typed with generics, the iterator returns objects of type Object. These need to be explicitly cast to type Map.Entry.