HashMap default types for K and V

I usually print my ads on a map, but I do some maint and found one without input. It made me think (Oh no!). What is the standard typing for a map ad. 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()); } 

these errors with incompatible types on Map.Entry. Therefore, if I print an ad with:

 Map<Object,Object> map = new HashMap(); 

then everything works well. So what is the default type in the declaration? Or am I missing something else?

+6
java collections generics
source share
3 answers

Type is java.lang.Object.

The for construct takes an Iterable type and calls its iterator method. Since the set is not defined using generics, the iterator returns objects of type Object. They must be explicitly cast to 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()); } 
+4
source share

The default type is missing.

Types in Java generics are only for checking compile time. They are erased at runtime and essentially go away.

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

+8
source share

HashMap is a collection of Think Think C ++ objects. Each card element is a "bucket" for storing data.
You place different types of data in buckets, the hash map should know that these are not all the same data types. If only one data type was placed in the hash file, you will receive a warning, but it will be compiled.

+1
source share

All Articles