Why Hashtable doesn't allow null key/value while Hashmap does.

Why Hashtable doesn't allow null key/value while Hashmap does.


In this post we will learn why Hashtable doesn't allow null key and null value while HashMap does.

How Hashtable and HashMap compute bucket Index.

Before checking this post, I would recommend understanding how HashMap and Hashtable works here


Hashtable and HashMap both uses the given key to compute the bucket index, if the given key is null how will the bucket index be calculated. Also, key can be object and equality of which is determined by calling hashcode and equals on that object, so if the key is null that contract is not fulfilled.

So to summarize, Hashtable doesn't allow null key to compute the bucket index. 

HashMap is newer where it has corrected the issues in Hashtable and allows one null key and value. 
HashMap handles the null key as a special case and it has reserved the index "0" for the null key-value.


Sample Program.

package javabypatel.misc;

import java.util.HashMap;
import java.util.Hashtable;

public class Test {
	public static void main(String[] args) {
		Hashtable<String, String> hashtable = new Hashtable<>();
		//hashtable.put(null, "null"); // throws NPE
		//hashtable.put(null, "null"); // throws NPE

		HashMap<String, String> hashmap = new HashMap<>();
		hashmap.put(null, null);        // No problem
		hashmap.put(null, "my-value");  // No problem

		System.out.println(hashmap.get(null)); // Return value
	}
}


Post a Comment