Differences between an ArrayList and a Vector in Java

DifferencesJavaObject Oriented ProgrammingProgramming

The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.

  • Elements can be inserted or accessed by their position in the list, using a zero-based index.

  • A list may contain duplicate elements.

  • In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following table.

  • Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.

Both ArrayList and Vector are implementation of List interface in Java. Both classes keeps the insertion order. But there are certain differences as well.

Differences

Following are the important differences between ArrayList and Vector method.

Sr. No. Key ArrayList Vector
1 Synchronization ArrayList is non-synchronized. Vector is synchronized.
2 Size ArrayList increments 50% of its current size if element added exceeds its capacity. Vector increments 100% of its current size if element added exceeds its capacity.
3 Legacy ArrayList is not legacy. Vector is a legacy class.
4 Speed ArrayList is faster being non-syncronized. Vector is slower being syncronized.
5 Iteration ArrayList uses iterator interface to traverse through elements. Vector can use both iterator or enumerator interface to traverse through elements.

Example

Following example shows how to create and add elements to ArrayList and Vector classes −

JavaTester.java

import java.util.ArrayList; import java.util.Vector; import java.util.List; public class JavaTester { public static void main(String args[]) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); List<String> list1 = new Vector<>(); list1.add("A"); list1.add("B"); list1.add("C"); list1.add("D"); System.out.println(list); System.out.println(list1); } }

Output

[A, B, C, D]
[A, B, C, D]

Example

Following example shows how to iterate ArrayList and Vector classes using iterator and enumerator respectively −

JavaTester.java

import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; public class JavaTester { public static void main(String args[]) { ArrayList<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); Iterator<String> iterator = list.iterator(); while(iterator.hasNext()) { System.out.print(" "+iterator.next()); } System.out.println(); Vector<String> list1 = new Vector<>(); list1.add("A"); list1.add("B"); list1.add("C"); list1.add("D"); Enumeration<String> enumerator = list1.elements(); while(enumerator.hasMoreElements()) { System.out.print(" " + enumerator.nextElement()); } } }

Output

 A B C D
 A B C D
raja
Updated on 19-Aug-2022 10:50:38

Advertisements