Tuesday, 8 December 2015

Difference between ArrayList and Vector in Java

Vector, just like ArrayList, is also a growable dynamic array. As of Java v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework.

With JDK 5 it was also retrofitted for generics and implements Iterable interface too which means it can also use enhanced for loop.

So, in many ways Vector is just like ArrayList apart from some differences and this post is about those differences between the ArrayList and Vector.

ArrayList Vs Vector in Java

  • ArrayList is not synchronized whereas Vector is Synchronized. Which means that the methods in the Vector class are Synchronized methods making Vector thread-safe and ready to use as-is in a multi-threaded environment.
    ArrayList, if needed in a multi-threaded environment, has to be synchronized externally using Collections.synchronizedList method which returns a synchronized (thread-safe) list backed by the specified list.
  • Refer How and why to synchronize ArrayList in Java to know how to synchronize an ArrayList.

  • A Vector, by default, doubles the size of its array when it needs to expand the array, while the ArrayList increases its array size by 50 percent.
  • As mentioned though Vector is retrofitted to implement the List interface it still has legacy methods which are not there in ArrayList. As Exp. methods like addElement(), removeElement(), capacity() which are there in Vector class but not in ArrayList.
  • Performance wise Vector is comparatively slower than the ArrayList because it is synchronized. That means only one thread can access method of Vector at the time and there is an overhead of acquiring lock on the object too.
  • For traversing an ArrayList as well as Vector, Iterator or ListIterator can be used. That Iterator/ListIterator is fail-fast and throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method.
    For Vector enumeration can also be used for traversing which is not fail-fast.

That's all for this topic Difference between ArrayList and Vector in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. Difference between ArrayList and LinkedList in Java
  2. How to join lists in Java
  3. How to sort arraylist of custom objects in Java
  4. How to remove elements from an ArrayList in Java
  5. Difference between HashMap and HashTable in Java
  6. Java Collections interview questions

You may also like -

No comments:

Post a Comment