HashMap vs Hashtable vs HashSet

I was reading about collection framework of Java. And was studying Hashtable, HashMap and HashSet. Its quite interesting to know the differences between them. In this post I will discuss these three with examples.

Hashtable

Hashtable is basically a datastructure to retain values of key-value pair.

  • It didn’t allow null for both key and value. You will get NullPointerException if you add null value.
  • It is synchronized. So it comes with its cost. Only one thread can access in one time
Hashtable<Integer,String>; cityTable = new Hashtable<Integer,String>();
cityTable.put(1, "Lahore");
cityTable.put(2, "Karachi");
cityTable.put(3, null); /* NullPointerEcxeption at runtime*/

System.out.println(cityTable.get(1));
System.out.println(cityTable.get(2));
System.out.println(cityTable.get(3));

HashMap

Like Hashtable it also accepts key value pair.

  • It allows null for both key and value
  • It is unsynchronized. So come up with better performance
HashMap<Integer,String> productMap = new HashMap<Integer,String>();
productMap.put(1, "Keys");
productMap.put(2, null);

HashSet

HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.

HashSet<String> stateSet = new HashSet<String>();
stateSet.add ("CA");
stateSet.add ("WI");
stateSet.add ("NY");

if (stateSet.contains("PB")) /* if CA, it will not add but shows following message*/
     System.out.println("Already found");
else
    stateSet.add("PB");
  • Patrick

    You should mention that Hashtable and HashMap both implement Map but HashSet implements Set !!! Map and Set are not meant for the same use. The Hash* is just an indication on how these Maps and Set are implemented…

  • http://www.pakzilla.com Tahir Akram

    Thanks Patrick for your comments. I will definitely update it.

  • Trent

    You also forgot LinkedHashSet, which is useful when you want to iterate in the order that items were inserted.

  • http://ssscripting.wordpress.com geo

    There’s also a LinkedHashMap, which you can use to iterate over the keys in insertion order.

  • teto

    There is also a EnumMap and EnumSet, that are optimized versions to be used with enums, the underlying implementation uses an array to hold the elements and thus the performance is better. Take a look at the javadocs, it could be interesting.

  • http://www.breun.nl/ Nils Breunese

    And don’t forget ConcurrentHashMap in the java.util.concurrent packages: http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html

  • http://www.merakarobaar.com Zia Ur Rahman Baig

    Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.

  • java hunter

    its better understanding for java beginners… thanks lot..

  • http://www.pakzilla.com/2009/08/24/hashmap-vs-hashtable-vs-hashset/ jetti

    Hi frds
    Thanks for posting………….

    • teddy

      yeah ..thanks fr posting

  • hasim

    HashSet Allows Duplicate , Please remove that ,if you want to check please run this program.

    HashSet set = new HashSet( true );
    set.add( new Integer( 3 ) );
    set.add( new Integer( 3 ) );

    Now tell me if it break or not.

    • Guest20

      This is just wrong. Execute fallowing Unit Test and you will recognize, that these Integer-Objects are not the same. Well HashSet may uses the HashCode and/or the equals Method which checks for value, but not for the real object.
      @Test public void it(){ Assert.assertTrue(new Integer(3) == new Integer(3)); }

      • http://twitter.com/tahirakram Tahir Akram

        appprove

  • Dhanaji

    Hi Hasim,

    It was in previous version….

    You have to check this code with latest java.

  • http://Website(optional) satyen

    HasSet don’t allowed the Duplicate if the mansion any duplicate value in HasSet program will run but the value will override/

  • Shashank

    Hey Thanks Tahir.
    This was very helpful and cleared my doubts.

  • AKBAR ALI

    Thanks dear

  • Vineet

    didn’t know this.. cool stuff !

  • anandh

    Thnx..a lot..got some ideas…!!!

  • Anon

    Thx a lot.
    :)

  • Anon

    Thx a lot.
    :)

  • Osama

    Much appreciated!! … do you know what is the complexity of searching a hashtable?…

    Thanks Osama

    • http://www.facebook.com/profile.php?id=10717024 David Ou

      Constant time lookups and inserts. You know the index, because of the hashing function.

  • Olena Kamentsev

    Helpful refresher! Thank you!

  • subramani

    simple and clear,,,

  • Krishnakanthpappu

    thnx. )

  • Ramesh

    nice one example sir…..thxs lots

  • Rohit5

    I think performance is key difference between HashMap vs Hashtable CHM is better in place of table.

  • Rohit5

    One more difference between Hashtable vs HashMap in Java is that former is a legacy class and initially not part of Collection API

  • Muhammad Ejaz Azeem

    “HashMap
    Like Hashtable it also accepts key value pair.
    It allows null for both key and value It is unsynchronized. So come up with better performance”It allows on one null key.

  • Pingback: HASHMAP VS HASHTABLE VS HASHSET | yizhaoee

  • m. riazio92

    Is there any difference between the access time of them? I mean searching in which one is faster when you have unique entry?

  • -|A|-

    Extremely Awesome Job, precise and simple… Bingo