What are the differences between ArrayList and Vector?
As the documentation says, a Vector
and an ArrayList
are almost equivalent. The difference is that access to a Vector
is synchronized, whereas access to an ArrayList
is not. What this 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; if you use an ArrayList
, this isn't the case. Generally, you'll want to use an ArrayList
; in the single-threaded case it's a better choice, and in the multi-threaded case, you get better control over locking. Want to allow concurrent reads? Fine. Want to perform one synchronization for a batch of ten writes? Also fine. It does require a little more care on your end, but it's likely what you want. Also note that if you have an ArrayList, you can use the Collections.synchronizedList
function to create a synchronized list, thus getting you the equivalent of a Vector
.
Differences
- Vectors are synchronized, ArrayLists are not.
- Data Growth Methods
Use ArrayLists if there is no specific requirement to use Vectors.
Synchronization
If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or simply modifies an element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
Collections.synchronizedList
is normally used at the time of creation of the list to avoid any accidental unsynchronized access to the list.
Data growth
Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.