Java – default type of HashMap for K and V

I usually type my map declaration, but I'm doing some maint and finding one without input It reminds me of (oh, no!) What is the default input for the 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());
}

Map. This error occurs when the types on the entry are incompatible So, if I enter a statement:

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

Deo gratias. So what is the default type set in the declaration? Or did I miss something else?

Solution

The type is Java lang.Object.

The for construct takes the iteratable type and calls its iterator method Because set does not use a generic type, the iterator returns an object of type object These need to be explicitly converted to map Entry type

Map map = new HashMap();
map.put("one","3rd");
for (Object o : map.entrySet()) {
    Map.Entry entry = (Map.Entry) o;
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>