«Back to Home

Core Java

Topics

Difference between ArrayList And Vector In Java

In Java, both ArrayList and Vector classes implement the list interface and both maintain an insertion order.
 
Differentiate between ArrayList And Vector

In Java, there are many differences between ArrayList and Vector classes, which are,

 ArrayList  Vector
ArrayList class is not synchronized. Vector class is synchronized.
ArrayList increments half (50%) of a current array size, if the number of an element increases. Vector increments full (100%) which means doubles the array size, if the total number of the element increases.
ArrayList class is introduced in JDK 1.2. and it is a not a legacy class. Vector is a legacy class.
ArrayList is very fast because it is non-synchronized. Vector is very slow because it is synchronized.
ArrayList class uses only Iterator interface to traverse the elements. Vector class uses enumeration interface to traverse the elements and it can use Iterator also.
 
Let’s see an example of ArrayList Class, given below.
 
Code
  1. import java.util.*;  
  2. public class CollectionsExample {  
  3.     public static void main(String args[]) {  
  4.         List < String > a = new ArrayList < String > ();  
  5.         a.add("Bob");  
  6.         a.add("Jack");  
  7.         a.add("Andy");  
  8.         Iterator i = a.iterator();  
  9.         while (i.hasNext()) {  
  10.             System.out.println(i.next());  
  11.         }  
  12.     }  
  13. }  
15

Output

16

In the example, shown above, we are using ArrayList to store and traverse the elements.
 
Now, let’s see an example of Vector Class, given below.
 
Code
  1. import java.util.*;  
  2. public class CollectionsExample {  
  3.   
  4.     public static void main(String args[]) {  
  5.         Vector < String > vt = new Vector < String > ();  
  6.         vt.add("Mia");  
  7.         vt.addElement("Harry");  
  8.         vt.addElement("Jack");  
  9.         Enumeration enm = vt.elements();  
  10.         while (enm.hasMoreElements()) {  
  11.             System.out.println(enm.nextElement());  
  12.         }  
  13.     }  
  14. }  
17

Output

18

In the example, shown above, we create Vector class, which uses enumeration interface.
 
Summary

Thus, we learnt that both ArrayList and Vector classes implement list interface, both maintain an insertion order and also learnt their differences in Java.