List implementation

List implementations are divided into general-purpose List implementations and special-purpose List implementations.

Generic List implementation

There are two generic List implementations - ArrayList and LinkedList. Most of the time, you will probably use ArrayList, which provides access by position and is faster. When you need to move multiple elements at the same time, you can give full play to the advantages of System.arraycopy. You can think of ArrayList as a Vector without synchronization.

If you need to frequently add elements to the head of the List or traverse the List and delete elements from inside, then you can consider using LinkedList. These operations require constant time in LinkedList, but linear time in ArrayList. But you will pay a price in performance, because access by position in LinkedList takes linear time, while in ArrayList it only takes constant time. If you want to use LinkedList, please test the performance of LinkedList and ArrayList in your system before you make a decision, usually ArrayList is faster.

ArrayList has an adjustment parameter - the initial value of the container, which represents the number of elements that the ArrayList can store before its data grows. LinkedList does not adjust parameters, and there are 7 optional operations, one of which is clone. The other six are, addFirst, getFirst, removeFirst, addLast, getLast, and removeLast. LinkedList also implements the Queue interface.

Special-purpose List implementation

CopyOnWriteArrayList is a List that implements copying to an array for backup. This implementation is very much like CopyOnWriteArraySet. No synchronization is required, and the iterator is guaranteed not to throw ConcurrentModificationException even during iteration. This implementation is well suited for maintaining a list of event handlers whose data rarely changes, but which is frequently iterated and potentially time consuming.

If you need synchronization, a Vector will be slightly faster than an ArrayList created using Collections.synchronizedList. But Vector will have some legacy operations, so please try to use the methods in the List interface when using Vector, or you are sure that you will not change the Vector implementation in the future.

If the size of the List is fixed -- that is, you won't be calling remove, add, or any bulk operations other than containsAll -- then you have a third option worth considering. That is Arrays.asList, the specific content will be discussed later.

Guess you like

Origin blog.csdn.net/oligaga/article/details/132638071