您的位置:首页 > 编程语言 > Java开发

java.util.ArrayList

2016-06-03 23:27 323 查看

java.util.ArrayList

api

List 接口的大小可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。


construct

ArrayList是一个顺序列表,是对一个数组的封装

/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access

/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;

elementData数组是存储数据的容器,size表示当前存储元素的个数

ArrayList有三个构造函数

ArrayList()

默认构造函数,lazey的思想,将elementData设置为一个空数组,在
add()
时初始化大小为10

ArrayList(int initialCapacity)
将elementData初始化为固定指定大小
this.elementData = new Object[initialCapacity]


ArrayList(Collection<? extends E> c)

用另一个集合的底层数组来构成新的ArrayList,
elementData = c.toArray();


Collection.toArray()
方法返回该集合的底层数组(ArrayList也是一个集合,实现了
interface Collection
)


构造函数
ArrayList(Collection<? extends E> c)
中还有一段代码,是为了处理bug 6260652

if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);

因为c.toArray返回的可能不是Object[].class类型,例如返回了String[].class类型,这里用
Arrays.copyOf
重新复制了一下数组,并且作了类型转化


主要方法实现

add

public boolean add(E e) {
ensureCapacityInternal(size + 1);扩充容量  // Increments modCount!!
elementData[size++] = e;//放入元素到数组
return true;
}

get

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: