It is a very common question in Java interviews. But if you has mentioned Java along with your Big data skills or you are working with Big data technologies using Java, then this is a mandatory question for you also. So in this we will discuss what is Vector and ArrayList, what are the differences between them and finally how choose between these two.
ArrayList
A dynamically growable collection that is used to stored objects in it.
Vector
A Vector is also a dynamically growable collection that can be used to store objects.
They both implement List interface, maintain insertion order and both provide the same functionalities, but there are some differences in their implementation.
Synchronization -
ArrayList is not synchronized whereas Vector is synchronized. Which means that multiple thread can work on ArrayList at the same time but Vector doesn't allow it. If a thread is inserting elements into ArrayList another thread can perform remove operation on the same ArrayList. In this cases we might get concurrent modification error due to multiple threads modification. So we need to synchronize the block of code doing these operations.
Release
Vector is a legacy class, it is introduced in 1.0 version of Java. ArrayList is not a legacy class, it is introduced in 1.2 version of Java.
Performance
ArrayList will be faster because it is not synchronized, so it allows multiple thread to work on it and provides the results faster. Vector gives worse performance compared to ArrayList because it is synchronized. It doesn't allow multiple thread to work on it. If thread is performing some operation, that thread acquires a lock on it and keeps the other threads waiting state until it releases the lock.
Data Growth
Both ArrayList and Vector can grow dynamically as and when required, but the way they grow is different. ArrayList always increments capacity by 50% if the number of elements in ArrayList reaches it's capacity. But Vector increments it's capacity by 100% when the number of elements in it reaches capacity.
Access to elements
ArrayList elements can be accessed using Iterator. Whereas elements of Vector can be accessed using Iterator as well as Enumerator.
How to choose between Vector and ArrayList or when to ArrayList and when to use Vector:
- ArrayList is not synchronized which means it allows multiple thread to work on it, but it might lead to system to run into issues. So in single threaded environment always prefer ArrayList. As Vector is synchronized and doesn't allow multiple threads to work on it, use Vector in multi-threaded environment.
- If you don't know the size of the data you are going to put in collection, then prefer Vector as it allows the user to set the increment value.
- If there is not specification to use any of them go with ArrayList.