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())
From the documentation:
The hash code of a map is defined to be the sum of the hash codes of each entry in the map's entrySet() view. This ensures that m1.equals(m2) implies that m1.hashCode()==m2.hashCode() for any two maps m1 and m2, as required by the general contract of Object.hashCode().
Since your HashMap (which is derived from AbstractMap) is initially empty, that sum is zero.
The hashCode for maps is defined as the sum of all hashcodes of the keys and values.
More precisely, Map.hashCode() is specified as:
Returns the hash code value for this map. The hash code of a map is defined to be the sum of the hash codes of each entry in the map's
entrySet()view.
This ensures thatm1.equals(m2)implies thatm1.hashCode()==m2.hashCode()for any two maps m1 and m2, as required by the general contract ofObject.hashCode().
And Map.Entry.hashCode() is defined as
Returns the hash code value for this map entry. The hash code of a map entry
eis defined to be:(e.getKey()==null ? 0 : e.getKey().hashCode()) ^ (e.getValue()==null ? 0 : e.getValue().hashCode())This ensures that
e1.equals(e2)implies thate1.hashCode()==e2.hashCode()for any two Entriese1ande2, as required by the general contract ofObject.hashCode.
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, use System.identityHashCode(map). This is a (more or less unique) number for each map, which will not change when the contents of the map changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With