Why Hashtable throws NullPointerException on adding null as a key or value?

We know that HashMap in java allows one key as null and multiple values as null.However,Hashtable
throughs null pointer exception if we add null as key or as value because
if we see internal implementation of Hashtable

 public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();

Highlighted parts in put method make it clear if the value in null throw NullPointerException and as hashCode method is called on the key so if the key is null then also it will through NullPointerException.

Hope it is clear.

Give you suggestion in comments.If you like the post Share with your friends on social network.
Why Hashtable throws NullPointerException on adding null as a key or value? Why Hashtable throws NullPointerException on adding null  as a key or value? Reviewed by JavaInstance on 11:29:00 AM Rating: 5

No comments:

Powered by Blogger.