Difference between ArrayList and Vector
ArrayList | Vector |
---|---|
1) ArrayList is non-synchronized which means multiple threads can work on ArrayList at the same time. | 1) Vector is synchronized which means multiple threads can’t work on vector at the same time. |
2) ArrayList increments (3/2 +1)of current array size(almost 50% of current capacity) if total number of element exceeds than its capacity. | 2) Vector increments 100% means doubles the array size if total number of element exceeds than its capacity. |
3) ArrayList is introduced in JDK 1.2.so it is not a legacy class. | 3) Vector is a legacy class. |
4) ArrayList gives better performance as it is non-synchronized. | 4) Vector operations gives poor performance as they are synchronized( thread-safe). |
5) ArrayList uses Iterator interface to traverse the elements. | 5) Vector uses Enumeration as well as Iterator interface to traverse the elements. |
Similarities between ArrayList and Vector
- Both Vector and ArrayList use growable array data structure.
- Both are ordered collection classes as they maintain the elements insertion order.
- Both Vector and ArrayList allows duplicate and null values.
- Both grows and shrinks automatically when number of element exceeds than its capacity.
ArrayList Example
import java.util.*;
public class MyArrayList {
public static void main(String args[]) {
// ArrayList declaration
ArrayList<Integer> al =new ArrayList<Integer>();
// Adding elements to the Arraylist
al.add(1);
al.add(2);
al.add(3);
al.add(1);
al.add(5);
//Displaying Arraylist elements
System.out.println(al);
}
}
Output:
[1, 2, 3, 1, 5]
Vector Example
import java.util.*;
public class MyVector {
public static void main(String args[]) {
// Vector declaration
Vector<Integer> vt =new Vector<Integer>();
// Adding elements to the Vector
vt.add(1);
vt.add(10);
vt.add(30);
vt.add(40);
vt.add(10);
//Displaying Vector elements
System.out.println(vt);
}
}
Output:
[1, 10, 30, 40, 10]