Vector is an analog to the ArrayList. So, from an API perspective, the two classes are very similar. They both use java Array internally to store the elements. There are still some major differences between these two classes and we will be going through them now...Synchronization:
Vectors are synchronized. This means that all of its methods are thread safe.
ArrayList on the other hand, is unsynchronized, making them, therefore, not thread safe.
Using synchronization will incur a performance hit. What it means is that all the threads accessing the same Vector object are blocked until the first thread completes its operation on the object. Due to this no two threads are using the object at the same time. Hence this enforces the data consistency.
Tips: use the Vector only where it is really necessary.
Capacity and Data growth:
As we discussed above, Vector and ArrayList both hold their data in Java Array object. However when size of the Array goes beyond its allocated space, there needs to be resizing to accommodate the new elements in the Array. The expansion of the Array object is done differently for Vector and ArrayList:
Vector defaults to doubling the size of its array.
ArrayList increases its array size by 50 percent.
Tips: There is a cost involved in adding new elements to these containers. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later.
It is advisable to initialize the capacity of these containers at the time of object creation.
e.g. Vector v = new Vector(initialCapacity);
Depending on the application, choose right value for initialCapacity.
Usage patterns
These containers perform Add/Remove/Get in constant time i.e. O(1) when Add/Remove is done either at the start or end of the list. However the cost increases when Add/Remove is done inside the list. Because in this case, the iterator has to identify the position in linear time i.e. O(n).
Tips: use plain old Array in place of these containers for the performance critical applications.
Speed
ArrayList is faster than Vector. Since Vector is synchronized it pays price of synchronization which makes it little slow.
Default Size
ArrayList in Java has no default size but Vector in Java has default size of 10.
that's all folks!!!
No comments:
Post a Comment