Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

key Entry as Empty String or null in HashMap

Tags:

java

hashmap

In Hashmap for null key the index is 0 but for Empty string what will be the index. I debug it and found that it is creating a linkedlist at the 0th index and storing both value there.

So why empty string value is storing in the 0th position and if it is calculating the index using the hashmap of the empty string then what will the hashcode of empty string.

HashMap<String, String> hm= new HashMap<>();
hm.put("", "");
hm.put(null, null);
like image 573
Inder Singh Avatar asked Oct 26 '25 09:10

Inder Singh


1 Answers

Because hashcode for an empty string returns 0, and that it is the same value for a null object. So you have a collision of hash, so it goes to the same cell.

* At least for the current implementation in the class String - that could change one day

like image 86
spi Avatar answered Oct 28 '25 00:10

spi