Search code examples
javahashmap

HashMap having null as key


How HashMap internally differentiate between null and 0 as key.

As per this post the hash code for null key is 0, Is it correct? If yes then both should go in same bucket at index 0 and there should be one value in the HashMap but this is not how HashMap works.

Can somebody explain me? what is the hash code for null key in HashMap?

Sample code:

HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(null, "abc");
map.put(0, "xyz"); // will it override the value for null as key?

System.out.println(map.get(null));  // abc
System.out.println(map.get(0));     // xyz

Solution

  • If yes then both should go in same bucket at index 0 ...

    Correct.

    and there should be one value in the HashMap

    Incorrect. There will be a separate entry for the two keys. This is guaranteed by the Map and HashMap specification; i.e. the javadocs say that there will be a separate entry for each distinct key. The implementation is required to meet the specification ... and it does.

    Prior to Java 8, the way that HashMap handles collisions is to chain together all of the entries that hash to the same bucket. The HashMap.get(key) logic will iterate the chain for the relevant bucket, looking for an entry that matches the key. (In your example code, there would be separate entries in the chain for the null and the Integer(0) keys.)

    In Java 8, it works the same to start with, but there is an optimization for the case where the keys all implement Comparable and the chains get too long. In this case, the long chains are converted into binary trees ... so that an O(N) chain scan turns into an O(logN) tree search.