Define Hashtable,HashMap and HashSet



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 come with its cost. Only one thread can access in one time
  1. Hashtable<Interger,String>; cityTable=new Hashtable<Interger,String>();
  2. cityTable.put(1,”Lahore”);
  3. cityTable.put(2,”Karachi”);
  4. cityTable.put(3,null); // NullPointerException at runtime
  5. System.out.println(cityTable.get(1));
  6. System.out.println(cityTable.get(2));
  7. 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 un-synchronized. So come up with better performance
  1. HashMap<Interger,String>; prodcutTable=new HashMap<Interger,String>();
  2. prodcutTable.put(1,”Keys”);
  3. prodcutTable.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.

  1. HashSet<String>; stateSet=new HashSet<String>();
  2. stateSet.add(“CA”);
  3. stateSet.add(“WI”);
  4. stateSet.add(“NY”);
  5. if(stateSet.contains(“PB”)) /* if CA,it will not add but shows following message */
  6. System.out.println(Already found);
  7. else
  8. stateSet.add(“PB”);

Use hashSet if you just want to have a set of object, HashMap if you want some mappings(key-value pair), Use Hashtable in multi threaded enviroment as its synchronized (alternatively you can use a synchronizedMap as well)

For More Information on Collections Visit UTIL PACKAGE

Share with SociBook.com

Related Post

  1. 1 Comment(s)

  2. By Ajit on Oct 23, 2010 | Reply

    I guess the best article i have ever came across

Post a Comment