Easy learning with example program codes

How hashmap stores null key?


HashMap extends AbstractMap class and implements the Map interface. It contains the elements in key-value pair form. It not maintains any order for its elements. It not allowed duplicate key. A HashMap can have only one null key and multiple null values.

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 is actually created as Array of linkedlist where index in array is find out by hashing on key.

package com.codesjava;
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("codesjava", 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(); = name; = id;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public int getId() {
		return id;
	public void setId(int id) { = id;
	public String toString() {
		return this.getId() + "-" + this.getName();
	public int hashCode() {
		//For simplicity we are returning id as hashCode value 
	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; 
        	return false;


Related Topics

Please follow and like us:
Posted in Java   

Core Java Tutorial

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki