I had read somewhere that we can add only one null object as a key to Hashmap object in java. But when I make object of any class and assign it as null and try to print hashcode of that object then it returns in null pointer exception. Then how hashmap calculates hashvalue of that null object as a key and how does it put in bucket?
2 Answers
Just had a quick peek at the implementation of HashMap and that determines the hash value for the key as follows:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
So for null keys the hashvalue always be 0 which also explains that there can be only 1 key with value null.
Hope this answers your question.