前言
集合中的collection接口下的常用类的关系
ArrayList中的成员变量
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//可以看到成员变量里有两个静态常量object数组。
/**
* 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
//transient关键字表示变量不再是对象持久化的一部分,该变量内容在序列化后无法获得访问。
初始化
第一种初始化:
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
第二种初始化:
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
第三种初始化:
不常见。略。
插入元素
void add(E);插入元素
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
// private int size; size未赋值时这里size是零。
elementData[size++] = e;
return true;
}
其中的ensureCapacityInternal方法
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
其中的 calculateCapacity方法和ensureExplicitCapacity方法
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//判断elementData是不是空的数组
return Math.max(DEFAULT_CAPACITY, minCapacity);
//返回minCapacity和静态常量DEFAULT_CAPACITY(10)中的较大值
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
//成员变量 protected transient int modCount = 0;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
ensureExplicitCapacity方法中的grow方法
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
//带符号右移。正数右移高位补0,负数右移高位补1,oldCapacity >> 1相当于除以二,
// 所以newCapacity是1.5倍的oldCapacity
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
// private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
newCapacity = hugeCapacity(minCapacity);
// newCapacity >MAX_ARRAY_SIZE时,newCapacity赋值为 Integer.MAX_VALUE
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
// copyOf()的第二个自变量指定要建立的新数组长度,如果该ArrayList对象实例第一次调用add方法,
//(debug时好好捋一遍流程可知)那么这里的newCapacity在grow方法里最后赋值为十
//所以说ArrayList初始长度默认是十,是在add方法里的grow方法里通过Arrays.copyOf
//方法完成的,而不是在构造器中直接初始化为十
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
//三元表达式,
void add(int,E);在特定位置插入元素
public void add(int index, E element) {
rangeCheckForAdd(index);//index>size或者<0则报错。
ensureCapacityInternal(size + 1); // 同上
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//把elementData数组里的元素从index开始往后移一位。
elementData[index] = element;
size++;
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
// arraycopy是一个静态本地方法,
* @param src the source array.
* @param srcPos starting position in the source array.
* @param dest the destination array.
* @param destPos starting position in the destination data.
* @param length the number of array elements to be copied.
移除元素
remove(Object):remove指定元素。
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
//把elementData数组里的元素从index开始往前移一位。
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
remove(index):remove指定位置元素。
public E remove(int index) {
rangeCheck(index);//index>size则报错
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//数组中index后的元素往前移动一位。
elementData[--size] = null; // clear to let GC do its work
//最后一个元素设为null
return oldValue;
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
其中涉及到的 fastRemove(int index)
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}