How hashmap stores null key?

In Hashmap one null key is allowed and multiple null values are allowed. Since hashcode of null is 0 so null key actually stored at index 0 in hashmap.

Hashmap in java actsually created as Array of linkedlist where index in array is find out by hashing on key.

package com.w3spoint;
 
import java.util.HashMap;
import java.util.Map;
 
public class Test {
	public static void main(String args[]){		
		Map<String, Site> hashMap = new HashMap<>();
		Site site = new Site("w3spoint", 1);
		//Insert element with null key
		hashMap.put(null, site);	
	}
}
 
class Site{
	private String name;
	private int id;
 
	public Site(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	@Override
	public String toString() {
		return this.getId() + "-" + this.getName();
	}
 
	@Override
	public int hashCode() {
		//For simplicity we are returning id as hashCode value 
		return this.id;
	}
 
	@Override
	public boolean equals(final Object obj) {
		if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final Site siteObject = (Site) obj;
        if(this.getName() == siteObject.getName() && 
        		this.getId() == siteObject.getId())
        	return true; 
        else
        	return false;
	}	
}

HashMap

Content Protection by DMCA.com
Please Share