Map map = new HashMap();
System.out.println("hashCode:"+map.hashCode()); //hashcode==0 why?
map.put("test","test");
System.out.println("hashCode:"+map.hashCode()); //hashcode be okay here
How can I get hashCode after Map map = new HashMap(); ? (like: new Object().hashCode())
The hashCode for maps is defined as the sum of all hashcodes of the keys and values.
More precisely, Map.hashCode() is specified as:
And Map.Entry.hashCode() is defined as
Your new map has no entries yet, thus the sum is 0. Everything is at is should be.
If you want a number like the unoverridden
Object.hashCode()would return, useSystem.identityHashCode(map). This is a (more or less unique) number for each map, which will not change when the contents of the map changes.