Tuesday, September 2, 2014

Java Collections

The Java Collections API's provide Java developers with a set of classes and interfaces that
 makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays, 
except their size can change dynamically, and they have more advanced behavior 
than arrays.
Guide to Selecting Appropriate Map/Collection in Java 
What is the difference between Enumeration and Iterator? 
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator 
has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface,
 because it has the methods only to traverse and fetch the objects, where as using Iterator 
we can manipulate the objects also like adding and removing the objects.
So Enumeration is used when ever we want to make Collection objects as Read-only.
Difference between HashMap and HashTable? Can we make hashmap synchronized? 

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);


This table is a good summary of commonly used collection implementation classes.
General-purpose Implementations:
Hash tableResizable arrayTreeLinked listHash table + Linked list
Collection Resources -

No comments:

Post a Comment