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

in #cn6 years 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.
ArrayList是基于数组实现的集合,可以包含null元素和可重复的元素,且是有序的。超过可用长度可以实现自动增加50%扩容。

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.
数组在内存地址中是连续的,所以按数组下标来访问元素性能很高,但如果按下标插入或删除元素需要用System.arraycopy()来移动部分受影响的元素,所以性能会变差。

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)方法可用读取指定下标的元素。
get7.png

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

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

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

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

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

3 How to delete?(如何删除?)
ArrayList提供了根据下标或者指定对象两种方式的删除功能。
remove.png
removeo.png

4.如何扩容?
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实例的容量,以减少递增式再分配的数量。
的得到.png

Sort:  

看不懂😂

Congratulations @abyte! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Congratulations @abyte! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You got more than 10 replies.
Your next target is to reach 50 replies.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Support the HiveBuzz project. Vote for our proposal!