Pages

Friday, 13 April 2012

Difference between HashMap and HashSet and HashTable

Hashtable
Hashtable is basically a datastructure to retain key-value pairs.
  • It doesn’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 at a time
HashMap
Like Hashtable it also accepts key value pairs.
  • It allows null for both key and value
  • It is unsynchronized. Hence, it comes up with better performance than HashTable
  • Implements the map interface
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.
Implements the set interface.

Concurrent HashMap :
A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

References :
1) http://docs.oracle.com/javase/tutorial/collections/index.html
2) http://www.amazon.com/dp/0596527756/?tag=stackoverfl08-20

No comments:

Post a Comment