ArrayList and Vector are both classes in Java that implement dynamic arrays, allowing flexible resizing. ArrayList is unsynchronized, faster, and grows by 50%, while Vector is synchronized, grows by doubling, and is legacy. ArrayList is generally preferred for better performance in single-threaded environments, whereas Vector is suitable for multi-threaded scenarios to prevent concurrent access issues.
Both are super easy and fast to implement and use. ArrayList and vectors are dynamic arrays. Dynamic simply means we can change their sizes whenever we want. Both of these classes are used to implement the list interface.
Now let's see what ArrayList and vectors are and what the difference is between ArrayList and vector.
Also read, Duck Number in Java
What is ArrayList?
An ArrayList is a resizable array that is a part of the java.util.package, and it is used to implement a list interface. As it helps create a dynamic array, the size is not required to be specified during creation.
As we add or remove elements from ArrayList, the size of ArrayList changes accordingly.
If the number of elements extends the capacity of ArrayList, the new size of ArrayList will increase by 50% of the present array size.
The syntax for the creation of ArrayList is as follows:
ArrayList<T> variable_name = new ArrayList<T>();
ArrayList is unsynchronized in nature. ArrayList allows multiple threads to work at the same time. Thus if a thread performs a task, the other thread doesn't need to wait to complete that task.
Program:
Output:
Explanation
In the above code of ArrayList in Java, the size of dynamically created array arr was initially zero, but whenever we added elements or removed some elements from the array, the size changed accordingly.
Also see, Swap Function in Java
What is Vector?
Vectors are very similar to ArrayList. Both use dynamically resizable arrays internally, and both implement the list interface. Vector has some legacy methods that are not present in the collection framework. One significant difference between ArrayList and Vector in Java is if the elements inside the vector exceed its capacity, the vector increments the size by 100%, doubling the array's size.
The syntax for the creation of ArrayList is as follows:
Vector<T> variable_name = new Vector<T>();
Another difference between ArrayList and Vector is the vector is synchronized in nature. Multiple threads cannot work on vectors at the same time. Therefore if a thread is performing a task, the other thread has to wait to complete that task.
Program:
Output:
Explanation
In the above code of vectors in Java, whenever we add elements to the vector its size gets changed respectively. Another important point to note is that whenever the vector reaches its capacity then the new capacity of the vector gets doubled to its current size.