可以介绍一下 ArrayList内部是如何实现数组的增加和删除的,因为数组在创建时长度是固定的,那么就有个问题我们往ArrayList中不断的添加对象,它是如何管理这些数组呢?
对于ArrayList,相信大家都很熟悉,在开发中比较常用的集合。先总体介绍一下ArryList的实现。
1.基于数组实现,是一个动态数组,其容量能自动增长。
2.ArrayList不是线程安全的,建议在单线程中使用,多线程可以选择Vector或CopyOnWriteArrayList。
3.实现了RandomAccess接口,可以通过下标序号进行快速访问。
4.实现了Cloneable接口,能被克隆。
5.实现了Serializable接口,支持序列化。
ArrayList源码解析
ArrayList继承了AbstractList并实现了List,RandomAccess, Cloneable, java.io.Serializable 接口,上面做了相应的介绍就不再阐述了。关键我们看两个重要的属性elementData和size。
/**
* The array buffer into which the elements of the ArrayList are stored.(ArrayList的元素的数组缓冲区存储)
* The capacity of the ArrayList is the length of this array buffer(ArrayList的容量是这个数组的长度缓冲区). Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
复制代码
transient Object[] elementData;
elementData:保存了添加到ArrayList中的元素。实际上,elementData个动态数组,我们能通过构造函数ArrayList(intinitialCapacity)来执行它的初始容量为initialCapacity;如果通过不含参数的构造函数ArrayList()来创建ArrayList,则elementData的容量默认是10。
//The size of the ArrayList
size: 动态数组的实际大小