Difference between Vector and ArrayList in Java

First of all, these two classes implement the List interface, and the List interface has a total of three implementation classes, namely ArrayList, Vector and LinkedList. List is used to store multiple elements, can maintain the order of elements, and allow repetition of elements. The relevant differences between the three concrete implementation classes are as follows:

ArrayList is the most commonly used List implementation class. Internally, it is implemented through an array, which allows fast random access to elements. The disadvantage of the array is that there can be no space between each element. When the size of the array is not sufficient, the storage capacity needs to be increased, and the data of the existing array must be copied to the new storage space. When inserting or deleting elements from the middle of the ArrayList, the array needs to be copied, moved, and the cost is relatively high. Therefore, it is suitable for random lookups and traversals, not for insertions and deletions.
Like ArrayList, Vector is also implemented through arrays. The difference is that it supports thread synchronization, that is, only one thread can write Vector at a certain time, avoiding the inconsistency caused by multiple threads writing at the same time, but it requires a high cost to achieve synchronization. , so accessing it is slower than accessing an ArrayList.
LinkedList uses a linked list structure to store data, which is very suitable for dynamic insertion and deletion of data, and the speed of random access and traversal is relatively slow. In addition, it also provides methods that are not defined in the List interface, which are specially used to operate the header and footer elements, which can be used as stacks, queues and bidirectional queues.
Looking at the Java source code, it is found that when the size of the array is not enough, the array needs to be re-created, and then the elements are copied into the new array. The size of the extended array of ArrayList and Vector is different.

Conclusion: The difference between ArrayList and Vector is as follows:

When the memory is insufficient, ArrayList is expanded by 50% + 1 by default, and Vector is expanded by 1 times by default.
Vector provides indexOf(obj, start) interface, ArrayList does not.
Vector belongs to the thread-safe level, but Vector is not used in most cases, because thread safety requires greater system overhead.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325753040&siteId=291194637