Difference between Arraylist and Vector in java in Java Collections.
I’ll be listing 4 important differences between java arraylist and vector data structures.
Java ArrayList Vs Vector
- ArrayList is not thread safe as its methods are not synchronized, whereas Vector’s methods are synchronized. So, in multithreading environment, we can use Vector without making any extra efforts of synchronization as we do with ArrayList shared by multiple threads.
ArrayList: public boolean add(E e)
Vector : public synchronized void addElement(E obj)
- ArrayList is faster than Vector as it includes a slight overhead due to synchronization.
- ArrayList increments 50% of current array size if number of element exceeds its capacity while Vector increments 100% i.e. double.
- Size increment can be fixed in Vector but not in an ArrayList. For example, if we want to allow vector to re-size by some number we can do so using Vector constructor. This way it will not increments size by 100%. An example below.
Java code example with comments for increasing size of Vector:
public class ClassTest {
public static void main(String[] args)
{
// Increases size by 100%,
Vector v_default = new Vector(5);// assign capacity by 5
System.out.println("Intial Capacity is " + v_default.capacity());
for (int j = 0; j < 6; j++) {
v_default.add(j);
}
System.out.println("Capacity After default increment "
+ v_default.capacity());
// vector constructor for fixed size increment
Vector v_incr = new Vector(5, 2);// capacity 5 and given size to grow is 2
System.out.println("Intial Capacity is " + v_incr.capacity());
for (int j = 0; j < 6; j++) {
v_incr.add(j);
}
System.out.println("Capacity After fixed increment "
+ v_incr.capacity());
}
}
Output:
Intial Capacity is 5
Capacity After default increment 10
Intial Capacity is 5
Capacity After fixed increment 7