Difference between ArrayList and Vector in Java
Java ArrayList and Vector both implements List interface and maintains insertion order. But there are some differences between ArrayList and Vector.
- Thread Safety (Synchronization)
- Data growth
- Traversing (Iterator)
Thread Safety (synchronized)
Vector is synchronized by default, and ArrayList is not.
What is Synchronization ?
When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. The synchronized keyword causes a thread to obtain a lock when entering the method, so that only one thread can execute the method at the same time. This is usually called making the class thread-safe . Without synchronization, it is not guaranteed in which order the reads and writes happen, possibly leaving the variable with garbage .
What this (Synchronization) means is that only one thread can call methods on a Vector at a time, and there's a slight overhead in acquiring the lock. It is important to note that, you can make ArrayList also synchronized by passing arraylist object to Collections.synchronizedList() method.
Internally, both the ArrayList and Vector hold onto their contents using an Array . Both can grow and shrink dynamically to maintain the optimal use of storage, however the way they resized is different. ArrayList is created with an default initial size of 10. When this size is exceeded, the collection is automatically increases to half of the default size that is 15. Vector increments 100% means doubles the array size if total number of element exceeds than its capacity.
ArrayList gives better performance as it is non-synchronized . Vector operations gives poor performance as they are thread-safe , the thread which works on Vector gets a lock on it which makes other thread wait till the lock is released. That means, in ArrayList two or more threads can access the code at the same time , while Vector is limited to one thread at a time.
ArrayList elements can be traversed using Iterator , ListIterator and using either normal or advanced for loop. Vector uses Enumeration interface to traverse the elements.
The vector was not the part of collection framework , it has been included in collections later. It can be considered as Legacy code. There is nothing about Vector which List collection cannot do. Therefore Vector should be avoided.