What Are The Differences Between A HashMap And A Hashtable In Java?

In this article, we will learn What Are The Differences Between A HashMap And A Hashtable In Java? As hashmap is non-Synchronised whereas hashtable is synchronized. And hashmap is allow a null Value whereas hashtable does not allow any null values, there are a number of such differences that we will difference here.

HashMap And A Hashtable

HashMap

There are certain points that we need to keep in mind before declaring hashMap so we will discuss one by one here.

  • It Allows Null Values and null Keys.
  • It is Non- Synchronised.
  • No Method in Synchronised
  • Their multiple Threads are allowed to operate simultaneously and which makes the object thread not safe.
  • Here threads are not kept waiting which makes it faster.
  • It was introduced in java version 1.2
  • It is said t be no Legacy.

For example both hashMap and hashTable are

class Ideone
{
    public static void main(String args[])
    {
        //----------hashtable -------------------------
        Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
        ht.put(101," ajay");
        ht.put(101,"Vijay");
        ht.put(102,"Ravi");
        ht.put(103,"Rahul");
        System.out.println("-------------Hash table--------------");
        for (Map.Entry m:ht.entrySet()) {
            System.out.println(m.getKey()+" "+m.getValue());
        }
 
        //----------------hashmap--------------------------------
        HashMap<Integer,String> hm=new HashMap<Integer,String>();
        hm.put(100,"Amit");
        hm.put(104,"Amit"); 
        hm.put(101,"Vijay");
        hm.put(102,"Rahul");
        System.out.println("-----------Hash map-----------");
        for (Map.Entry m:hm.entrySet()) {
            System.out.println(m.getKey()+" "+m.getValue());
        }
    }
}

Hashtable

For the hashtable, there are a few points to keep in mind let’s discuss them here

  • It does not allow Null Values and null Keys.
  • It is Synchronised.
  • Methods are in Synchronised
  • Here no multiple Threads are allowed to operate simultaneously and which makes the object thread-safe.
  • Here threads are kept waiting, As it works in a synchronized manner which makes it slower, which reduces the performance.
  • It was introduced in java version 1.0.
  • It is said t be a Legacy.

Learn More about What Are The Differences Between A HashMap And A Hashtable In Java? at: Hash map and hash table difference

And Also visit Java Tutorials and Solutions for the list of all the topics and solutions of problems and also visit at How Immutable Is Different from Mutable Types, In python Programming for other  informantion.

Leave a Comment

%d bloggers like this: