0

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 2

2

If key is null the value is put into the bucket with index 0.

if (key == null)
  return putForNullKey(value);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.