Have a Question?

If you have any question you can ask below or enter what you are looking for!

Difference between HashMap & Hashtable in Java?

Difference between HashMap & Hashtable in Java?

Example

package com.java4us;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

class Test {
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put(101, "Welcome");
        map.put(102, "To");
        map.put(103, "Java4us");
        map.put(104, "Dot");
        map.put(105, "Com");
        System.out.println(map); // {101=Welcome, 102=To, 103=Java4us, 104=Dot, 105=Com}
        Set s = map.keySet();
        System.out.println(s); // [101, 102, 103, 104, 105]
        Collection c = map.values();
        System.out.println(c); // [Welcome, To, Java4us, Dot, Com]
        Set set = map.entrySet();
        System.out.println(set); // [101=Welcome, 102=To, 103=Java4us, 104=Dot, 105=Com]
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry m1 = (Map.Entry) iterator.next();
            System.out.println(m1.getKey() + ".." + m1.getValue());
            if (m1.getValue().equals("Dot")) {
                m1.setValue(".");
            }
        }
        System.out.println(map);    //{101=Welcome, 102=To, 103=Java4us, 104=., 105=Com}
    }
}

How to get synchronized HashMap object

By-default HashMap is non-synchronized but we can get the synchronized version of HashMap by using synchronizedMap() method of collections class. 

Differences between HashMap and HashTable 

Number HashMap Hashtable
1 Every method present in HashMap is not-synchronized Every method present is synchronized
2 At a time only multiple threads are allowed to operate on the HashMap object and hence it is not thread-safe. At a time only one thread is allowed to operate on Hashtable and hence it is thread-safe
3 Relatively performance is high because threads are not required to wait to operate on the HashMap object. Relatively performance is low because threads are required to wait to operate on  Hashtable object.
4 Null is allowed for both key and value Null is not allowed for keys and values otherwise we will get NullPointerException
5 Introduced in 1.2 version and it is not legacy Introduced in 1.0 version and it is legacy.

Leave a Reply

Your email address will not be published. Required fields are marked *