views:

588

answers:

3

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?

+6  A: 

There is no default type.

The types in Java generics are only for compile-time checking. They are erased at runtime and essentially gone.

Think of generics as a static helper to a) better document your code, and b) enable some limited compile-time checking for type safety.

davetron5000
+1  A: 

HashMap is a collection of objects, Think C++ containers. Each element of the map is a "bucket" to hold data.
You are putting different types of data in the buckets, the hashmap needs to know that these are not all the same data type. If only one type of data was placed in the hashmap, you would get a warning but it would compile.

WolfmanDragon
+3  A: 

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.

Map map = new HashMap();
map.put("one", "1st");
map.put("two", new Integer(2));
map.put("three", "3rd");
for (Object o : map.entrySet()) {
 Map.Entry entry = (Map.Entry) o;
 System.out.println(entry.getKey() + " -> " + entry.getValue());
}
McDowell