Consider the following Code :
import java.util.*;
class Employee {
String name;
public Employee(String nm) {
this.name=nm;
}
}
publ
If you pass null
as map key, it will go to 0 bucket
. All values of null key will go there. That is why it returns same value, cause all keys you are providing are null
and are in the same bucket of your HashMap.
HashMap
does not call hashcode when null is passed as key and null Key is handled as special case.
HashMap
puts null key in bucket 0 and maps null as key to passed value. HashMap does it by linked list data structure. HashMap uses linked list data structure internally.
Linked list data structure used by HashMap
(a static class in HashMap.java
)
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
}
In Entry class the K is set to null and value mapped to value passed in put method.
While in Hashmap
get method the checks if key is passed as null. Search Value for null key in bucket 0.
Hence there can only be one null key in one hashmap
object.
Incase of null key , Hashmap implementation consider it as special case and doesnot call hashCode method instead it stores Entry object to 0 bucket location.
When you put NULL to HashMap there is special check if you are trying to put NULL as key (called putForNullKey()). It is special case and works not like you are trying to put some object which is not null, and as you may see it even doesn't go to hash calculation.
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
A HashMap can only store one value per key. If you want to store more values, you have to use a MultivalueHashMap (Google Guava and Apache Commons Collections contain implementations of such a map).
e1 and e2 have the value null, since you don't assign any object to them. So if you use those variables, the key of that map entry is also null, which leads to your result. Null doesn't have any hashcode, but is tolerated as key in the HashMap (there are other Map implementations which don't allow Null as key).