The realization principle of ArrayList in Java - Java ArrayList实现原理

in cn •  11 months ago

ArrayList is a collection based on array, which can contain null elements and repeatable elements, and is orderly. Over 50% of the available length can be automatically increased.

Arrays are continuous in memory addresses, so access to elements by array subscript is very high, but if inserting or deleting elements according to the subscript requires System.arraycopy () to move some of the affected elements, the performance will be worse.

ArrayList is non thread safe, we can use the Vector collection instead of the multi thread access environment, or implement the thread synchronization Collections.synchronizedList (New ArrayList ()) by the Collections tool class.
ArrayList是非线程安全的,在多线程访问的环境下我们可以使用Vector集合替代,或者通过Collections集合工具类来实现线程同步Collections.synchronizedList(new ArrayList())。

1 How to read? (如何读取?)
通过get(int index)方法可用读取指定下标的元素。

2 How to store?(如何存储?)
2.1 set(int index, E element) 用指定元素替换指定位置上的元素。

2.2 add(E e) 用指定的元素添加到此列表的尾部.

2.3 add(int index, E element) 将指定元素添加到指定下标位置

2.4 addAll(Collection<? extends E> c) 将该collection中的所有元素添加到此列表的尾部。

3.5 addAll(int index, Collection<? extends E> c) 从指定的位置开始,将指定collection中的所有元素插入到此列表中。

3 How to delete?(如何删除?)

Every time an element is added to an array, it is necessary to check whether the number of elements added is beyond the length of the current array, and if it goes beyond, the array will be dilatant to meet the need for adding data. Array expansion is achieved through an open method called ensureCapacity (int minCapacity). Before adding a large number of elements, I can also use ensureCapacity to manually increase the capacity of ArrayList instances, so as to reduce the number of incremental redistribution.
每当向数组中添加元素时,都要去检查添加后元素的个数是否会超出当前数组的长度,如果超出,数组将会进行扩容,以满足添加数据的需求。数组扩容通过一个公开的方法ensureCapacity(int minCapacity)来实现。在实际添加大量元素前,我也可以使用ensureCapacity来手动增加ArrayList实例的容量,以减少递增式再分配的数量。

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!