In many ways Vector class in Java is just like ArrayList apart from some differences and this post is about those differences between the ArrayList and Vector in Java.
There are many similarities between Vector and ArrayList classes 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.
ArrayList Vs Vector in Java
- ArrayList is not synchronized whereas Vector is Synchronized. Which means that the methods in
the Vector class are Synchronized 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. - 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 Example 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.
Refer How and why to synchronize ArrayList in Java to know how to synchronize an ArrayList.
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
You may also like-
No comments:
Post a Comment