Difference between ArrayList and Vector
ArrayList and Vector both implements List interface and maintains insertion order.
However, there are many differences between ArrayList and Vector classes that are given
below.
ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList increments 50% of current array size Vector increments 100% means doubles the array
if the number of elements exceeds from its size if the total number of elements exceeds than
capacity. its capacity.
3) ArrayList is not a legacy class. It is introduced
Vector is a legacy class.
in JDK 1.2.
Vector is slow because it is synchronized, i.e., in a
multithreading environment, it holds the other
4) ArrayList is fast because it is non-synchronized.
threads in runnable or non-runnable state until
current thread releases the lock of the object.
5) ArrayList uses the Iterator interface to traverse A Vector can use the Iterator interface
the elements. or Enumeration interface to traverse the elements.
Example of Java ArrayList
Let's see a simple example where we are using ArrayList to store and traverse the elements.
import java.util.*;
class TestArrayList21{
public static void main(String args[]){
List<String> al=new ArrayList<String>();//creating arraylist
al.add("Sonoo");//adding object in arraylist
al.add("Michael");
al.add("James");
al.add("Andy");
//traversing elements using Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Example of Vector
1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
9. Enumeration e=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. }
13. }
14. }