Hello dude ! today we will talk about why HashTable doesn't allow key-value as a null while HashMap does??.........so lets go without wasting the time 😇😇😇.
We will discuss here this whole content into two parts. First we talk about HashTable then will come over HashMap.
So lets down with HashTable 😇😇😇😇😇.......
In the above code you can see that, sun people didn't allow 'null' value as a key and value. If you supply value as a null, it will throw NullPointerException as you can see in source code. If you supply key as a null, it will also throw NullPointerException due to 'int hash = key.hashCode()' line because key is null so you can't invoke any method on null reference.
As you can see here, put(K key,V value) method is overridden by HashMap class which is coming from Map interface. So if you want to see the real implementation of put method ,need to go inside implementation of hash(key) because this guy is responsible for generating hashCode for supplied key.. 😆😆😆😆😆😆😆..so...lets come...
As you can see here, supplied key is null, it return 0 as hashCode else go for actual hashCode.
We will discuss here this whole content into two parts. First we talk about HashTable then will come over HashMap.
So lets down with HashTable 😇😇😇😇😇.......
HashTable - java.util.Hashtable
Hashtable is a class which came with the first version of java. When it was released Java engineers tried to discourage the use of null keys or maybe did not realize its usefulness. So, they did not allow it in the Hashtable. Here is internal code of put method....In the above code you can see that, sun people didn't allow 'null' value as a key and value. If you supply value as a null, it will throw NullPointerException as you can see in source code. If you supply key as a null, it will also throw NullPointerException due to 'int hash = key.hashCode()' line because key is null so you can't invoke any method on null reference.
HashMap - java.util.HashMap
In case of HashMap, it allows null keys and values but you can pass key as null only once while value can pass multiple times. Now I will show you here what happens when you pass null as a key. For null key , the value of hashCode will be 0. Here is internal implementation of HashMap
As you can see here, supplied key is null, it return 0 as hashCode else go for actual hashCode.
0 comments:
Post a Comment