Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does hashCode() return zero before items are added to HashMap?

Tags:

java

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())

like image 480
Koerr Avatar asked May 03 '26 09:05

Koerr


2 Answers

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.

like image 104
thkala Avatar answered May 05 '26 00:05

thkala


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 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().

And Map.Entry.hashCode() is defined as

Returns the hash code value for this map entry. The hash code of a map entry e is defined to be:

(e.getKey()==null   ? 0 : e.getKey().hashCode()) ^
(e.getValue()==null ? 0 : e.getValue().hashCode())

This ensures that e1.equals(e2) implies that e1.hashCode()==e2.hashCode() for any two Entries e1 and e2, as required by the general contract of Object.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.

like image 30
Paŭlo Ebermann Avatar answered May 04 '26 23:05

Paŭlo Ebermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!