Sunday 6 September 2015

Difference between Vector and ArrayList in Java

One of the classic question from from Java interviews is, "what is difference between Vector and ArrayList?" You might have seen this in on your own interviews as well. Though both are implementation of List interface from JDK 1.4 onward, the key difference between them is Vector is not a thread-safe and synchronized Collection but ArrayList is not synchronized. Which means if multiple threads tries to add and remove elements from Vector, it will still be Ok, but ArrayList's structure may be destroyed. If you remember this key factor then you can automatically derive several other differences between Vector and ArrayList las shown below.



Vector vs ArrayList


1.Vector is thread-safe but ArrayList is not thread-safe and you cannot share it between multiple threads, if one of them modifies the list.

2. Vector achieved its thread-safety by synchronizing  add(), remove(), get(), set() and other methods, due to which its slower than ArrayList which provides direct access.

3. Vector is a legacy class, which was retrofitted in JDK 1.4 to implement List interface. Any improved e.g. performance or security related enhancement is more likely to be done on ArrayList than Vector.  That''s why any new code should be written using ArrayList class and other modern thread-safe List e.g. CopyOnWriteList.

4. Vector supports Enumeration to allow a client to iterate over all its elements, ArrayList supports more modern Iterator, which also allows you to remove elements from List while iterating.

Here is some more differences in nice tabular format :

Difference between Vector and ArrayList in Java


These are some of the useful differences between Vector and ArrayList class, which will help you during Java interviews.

No comments:

Post a Comment