Monday 5 December 2011

Difference between Vector and ArrayList in java?

ArrayList and Vector are very similar.Both of them represent a dynamically growable array ,where element can be stored and accessed using index. ArrayList is a part of the Java Collection Framework, and has been added with version 1.2, while Vector is an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface.

The main difference is that Vector is a synchronized object(i.e. all the methods in Vector class are synchronized) ,while ArrayList is not.

Any method that touches the Vector's contents is thread safe.That means the thread has to obtain a lock before excecuting any of the methods in Vector object.Only one thread can have the lock at a time.Once it finish the method execution ,can hand it over to other threads.Because two threads can't access one vector object simultaneously,it will create performance overhead.Hence use Vector only when you feel that ,there is a really need for synchronization.


ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe.With that difference in mind, using synchronization will incur a performance hit.So if you don't need a thread-safe collection, use the ArrayList don't use Vector.

A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements.If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value using Vector(int initialCapacity, int capacityIncrement); constructor.

ArrayList can be synchronized using the java collections framework utility class and then ArrayList itself can be used in place of Vector.
Collection.synchronizedList(List list);

1 comment: