Friday, February 4, 2011

Difference between HashMap and HashTable? Can we make

1. The HashMap class is roughly equivalent to Hashtable, except that
it is unsynchronized and permits nulls. (HashMap allows null values as
key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain
constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the
Hashtable isn't.


Note on Some Important Terms
1) Synchronized means only one thread can modify a hash table at one
point of time. Basically, it means that any thread before performing
an update on a hashtable will have to acquire a lock on the object
while others will wait for lock to be released.
2) Fail-safe is relevant from the context of iterators. If an iterator
has been created on a collection object and some other thread tries to
modify the collection object "structurally”, a concurrent modification
exception will be thrown. It is possible for other threads though to
invoke "set" method since it doesn’t modify the collection
"structurally”. However, if prior to calling "set", the collection has
been modified structurally, "IllegalArgumentException" will be thrown.
HashMap can be synchronized by Map m = Collections.synchronizeMap
(hashMap);

No comments:

Post a Comment