What is the difference between ArrayList and vector in java

What is the difference between ArrayList and vector in java?

This is one of the favorite interview question and very important to know the difference between the two because we need to use lot of those collection while writing the code. So it is essential to understand the differences between ArrayList and Vector for its use in the code.




Difference between Vector and ArrayList


Lets see the difference between Vector and ArrayList one by one :

1. First difference is very simple which is Vector is synchronized while ArrayList is not. Then question comes what do you mean by Vector is synchronized?? Answer is simple methods in Vector such as add(), remove() are synchronized which makes it thread-safe and thus we call it as synchronized so it is preferably used in multi threaded environment. And in case of ArrayList you will not find the methods made synchronized.

2. When we talk in terms of speed ArrayList is more faster than Vector reason is same Vector is synchronized.

3. Though both Vector and ArrayList are dynamically resizable there is a difference in the way they resized. Vector has size defined as threshold and it increase its value as per specified in capacityIncrement. In case of ArrayList Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. You can use ensureCapacity to add large number of elements which can reduce the incremental reallocation.

4. When ArraList returns enumeration of items such as Iterator and ListIterator these are fail-fast , but in case of Vector it is not the case.

These are some of the key differences between Vector and ArrayList in java. If you know other differences you can add more via comments :)
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment