Difference between ArrayList and Vector in Java

 


ArrayList and Vector are the important collection classes which used in Java. And also widely asked in interview about their difference and similarities between these 2 classes. Before looking into the difference and similarities between these two classes lets discuss some of the collection classes and interface in Java Collection framework. Below hierarchy diagram will give you the brief structure of the interface and classes in Collection framework like what are all the classes derived from different interface. 


Java Collections


Similarities:

  • Both ArrayList and Vector implements List interface.
  • Both ArrayList and Vector are ordered collection and allow duplicate and null values.
  • Both ArrayList and Vector are index based and values can retried by using index, which means internally it uses array as data structure to store the values. 
  • While initializing both ArrayList and Vector size will be 10 by default.


Differences: 

  • Vector is thread-safe and ArrayList is non thread-safe, which means Vector is synchronized and ArrayList is not. Suppose if we using any multi-threading or concurrent process then Vector will be best suited and other ways ArrayList will be best.
  • Performance wise Vector will be slow since its synchronized. 
  • Vector introduced in first version of JDK and from JDK 1.2 its merged with Java Collection framework and its implements List interface. Where as ArrayList introduced in JDK 1.2 along with Collection framework
  • By default both ArrayList and Vector increment the size automatically. The difference is ArrayList will increments its array size by half of its size, where as Vector will doubles the size of its array when its size is increased by default suppose if we didn't set the capacity Increment size.
  • Vector's capacity size increment can be set to any number when we initialize  where as ArrayList we can't. 


ArrayList initialize:

ArrayList<String> arr = new ArrayList<String>(); // Default initialCapacity = 10

ArrayList<String> arr = new ArrayList<String>(100); // initialCapacity = 100

Vector initialize:

Vector<String> vec = new Vector<String>(); // Default initialCapacity = 10

Vector<String> vec = new Vector<String>(100); // initialCapacity = 100

Vector<String> vec = new Vector<String>(100,10); // initialCapacity = 100 and capacityIncrement = 10


No comments:
Write comments