Sunday, May 26, 2013

Array List Vs Vector




Parameters
ArrayList
Vector
Synchronization

Not-synchronized. The list should be wrapped using the Collections.synchronizedList method

Synchronized
Data Growth Methods

 When we insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. ArrayList increases its array size by 50 percent. 

newCapacity = (oldCapacity * 3)/2 + 1;
Vector defaults to doubling the size of its array.
newCapacity = (capacityIncrement > 0) ?
                (oldCapacity + capacityIncrement) : (oldCapacity * 2)
Default Size
Constructs an empty list with an initial capacity of 10.

Constructs an empty vector with internal data array size of 10 and its standard capacity increment is zero.

Traversal
Uses Iterator which are
 are fail-fast. i.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException . The fail-fast behavior of iterators can be used to detect bugs.
Uses Iterator/Enumerator. The Enumerations returned by the methods of classes like Hashtable, Vector are not fail-fast that is achieved by synchronizing the block of code inside the nextElement()method that locks the current Vector object which costs lots of time.