Yes, this is a question that too many people have encountered, discussed, and explained.
To deepen your memory, I decided to write an article to record it.
The first thing you want to talk about is:
Vector was generated before the collections API, and arraylist was introduced as part of the collection framework at JDK. they all use an obejct [] internally to store elements.
OK. Now their differences are as follows:
1. Thread Security
The vector is synchronized, while the arraylist is not.
Because vector is synchronized, It is thread-safe.
Similarly, because vecotr is synchronous, it requires additional overhead to maintain the synchronization lock, so it is slower than arraylist (theoretically)
Of course, if you have a preference for arraylist, you can also use collection. synchronizedlist (list) to get a thread-safe list.
2. capacity growth
Vector allows you to set capacityincrement. In this way, when you need to expand the size of the array each time, the vector tries to set according to the preset capacityincrement, the arraylist doubles the array size.
For example, if we have the same vector and arraylist with a length of 10, we set the capacityincrement of the vector to 1.
When we insert 11th objects, the vector will change the length to 11, allocate space, and then add the object. The arraylist will allocate 20 objects, then add the object.
If the capacityincrement is set to 0 or a negative value, the vector will be the same as the arraylist, And the array size will be doubled each time.
3. Performance Comparison
As we have already said above, because the vector is synchronized, And the arraylist is not, the performance of the vector is a little bit better than that of the arraylist, so it is better to use performance for security.
However, according to Jack Shirazi's article on onjava, it seems that this is not a problem. He believes that for the current JVM, the performance difference between the two classes on the synchronization issue is even worse than that caused by environment changes during each test.
Consequently vector is thread-safe, and arraylist isn' t. this makes arraylist faster than vector. for some of the latest JVMs the difference in speed between the two classes is negligible: strictly speaking, for these JVMs the difference in speed between the two classes is less than the variation in times obtained from tests comparing the performance of these classes. ---- the performance of Java's lists
In this case, the performance difference should be small.
So, as a conclusion.
Most people come to the same conclusion:
In general, we recommend that you use arraylist. If you need synchronous control, you can use vector or collection. synchronizedlist (list) is re-transferred, unless not so .. otherwise, the code is written to people. in the case of no harm, writing according to the common rule will undoubtedly make the code readers understand it more quickly.