ArrayList vs Vector in Java? Interview Question Answer (original) (raw)
ArrayList vs Vector in Java
ArrayList and Vector are the two most widely used Collection classes in Java and are used to store objects in an ordered fashion. Every Java programmer which is introduced to Java Collection Framework either started with Vector or ArrayList. For beginners Difference between Vector and ArrayList in Java and LinkedList vs ArrayList are the two most popular Java Interview questions. ArrayList vs Vector is not only important from an interview perspective but also on the effective use of Java Collection API.
After reading this article you will know when to use Vector in Java, When to use ArrayList in Java, and would be able to compare ArrayList vs Vector over several important parameters like Speed, Synchronization, Code quality etc.
1. Bother Vector and ArrayList are derived from AbstractList and implements List interface, which means both of them are ordered collection and allows duplicates.
2. Another similarity between Vector vs ArrayList is that both are index based Collection and you can use get(index) method to retrieve objects from Vector and ArrayList.
Vector vs ArrayList in Java
In last section we saw some common properties between both of them and its time to see How much ArrayList and Vector are different to each other.
1. Synchronization
the first and most common difference between Vector vs ArrayList is that Vector is synchronized and thread-safe while ArrayList is neither Synchronized nor thread-safe. Now, What does that mean? It means if multiple thread try to access Vector same time they can do that without compromising Vector's internal state. Same is not true in case of ArrayList as methods like add(), remove() or get() is not synchronized.
2. Speed
The second major difference on Vector vs ArrayList is Speed, which is directly related to previous difference. Since Vector is synchronized, its slow and ArrayList is not synchronized its faster than Vector.
The third difference on Vector vs ArrayList is that Vector is a legacy class and initially it was not part of the Java Collection Framework. From Java 1.4 Vector was retrofitted to implement List interface and become part of Collection Framework.