Java源码分析之ArrayList
特点
- 有序
- 元素可以重复
属性
private transient Object[] elementData;
private int size;
解读:elementDate存储数据,size表示包含元素的数量
构造方法
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public ArrayList() {
this(10);
}
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
解读:共3个构造方法,第一个方法指定数组的长度;第二个方法默认数据长度10;
重要方法
add(E e):尾部添加一个元素
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
解读:先调整数组的长度,超过数组长度的话,grow方法自增一半.
index(Object o)
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
解读:从前到后遍历数组元素依次与目标对象比较,查询效率不高。
lastIndexOf则从后向前。
remove(Object o)