When to prefer Vector vs ArrayList?
By functionality, both are very similar. Both are derived from List interface. The most important difference is that Vector methods are synchronized where as ArrayList methods are not. In a multithreaded environment, when a number clients access same instance where data is very critical and important, it is advised to go for Vector. It is because synchronized methods allow only one client to access at a time. But, the other side of the coin is loss of performance (due to synchronization). If the data is not important, it is better to prefer ArrayList. The added advantage is high performance.
In the original release of Vector with JDK 1.0, the addition of elements is done with addElement() and retrieval is done with elementAt() methods. ArrayList released with JDK 1.2, being a member of collections framework, can use add() and get() methods for addition and retrieval of elements. These methods also can be used by Vector due to backward compatibility as Vector implements List interface.
The default capacity of Vector is 10 or can be custom declared by choosing the overloaded constructors. Such capacity concept does not exist with ArrayList.
For iterating the elements, the JDK 1.0, uses Enumeration. ArrayList uses Iterator. Iterators are fail-fast (or fail-safe) but Enumerations methods are not.
Vector methods are synchronized. Here, synchronized means, when one thread is updating the vector, another thread cannot access. The first thread acquires lock on the vector; when locks, other thread would wait until the first one relinquishes the lock.
Fail-safe or fail-fast are used with iterators. When an iterator returned by a collections class is on iteration, the collections class cannot update the collections object. That is, add, remove, set etc. cannot work. Both, the iterator and collections object, cannot modify the collections object at the same time; if done, JVM throws ConcurrentModificationException.
The collections framework includes a facility to convert any collections class into synchronized. Now let us obtain a synchronized version of array list.
ArrayList al = new ArrayList();
List myList = Collections.synchronizedList(al):
In the above two statements, al methods are not synchronized where as myList methods are synchronized.