Introduction to ArrayList
An ArrayList is an array queue, the equivalent of a dynamic array. Compared to arrays in Java, its size can grow dynamically. It inherits AbstractList and implements List, RandomAccess, Cloneable, java.io.Serializable interfaces.
- AbstractList, List provides add, delete, modify, iterate, etc.
- RandmoAccess provides random access
- Cloneable provides functionality that can be cloned
- Serializable provides serialization functionality
- Unlike Vector, operations in ArrayList are not thread-safe! Therefore, ArrayList is recommended for single-threaded applications, whereas Vector or CopyOnWriteArrayList can be used for multi-threaded applications.
Properties of ArrayList
|
|
ArrayList constructor
|
|
Method of ArrayList
Let’s take a look at how ArrayList is designed using a few of the more classic methods.
The first is to add methods, adding methods a total of three:
|
|
If you look closely at the top three added methods, they all call the ensureCapacityInternal method, which takes the array capacity required to perform the current add operation. It calculates whether the array needs to be expanded based on the parameters passed and completes the expansion if so. The difference is that the top two methods add only one element, so addAll passes size+1, whereas addAll passes size+ the length of the collection because it is an added collection.
Then look at the implementation of this method:
|
|
That’s how ArrayList dynamically expands. Note that ArrayList dynamically expands by replacing the original array with a new one:
|
|
Next, delete:
|
|
Note that deleting an element is also done through the underlying methods.
Now it’s relatively easy to look at get and set.
|
|
You can see why you’ve been told that ArrayList queries are more efficient to modify and less efficient to add and delete.
Serializable ArrayList can be serialized, but the array elementData is transient. ArrayList can be Serializable, but the array elementData is transient.
|
|
Due to limited space, this article only lists the above code. The full source code of ArrayList can be found at github.com/shiyujun/sy… !!!!!!!!!