您的位置:首页 > 其它

ArrayList源码解析

2016-07-29 20:16 218 查看
android-sdk/sources/android-23/java/util/ArrayList.java

属性:

最小扩容量:12

private static final int MIN_CAPACITY_INCREMENT = 12;


元素个数(不是容量):

int size;


底层存储方式:

transient Object[] array;


三种构造方法

默认初始化一个空对象数组

参数为容量,需处理参数为负值、参数为0情况

参数为一个Collection接口类型的集合

扩容

@Override public boolean add(E object) {
Object[] a = array;
int s = size;
if (s == a.length) {
//add扩容
Object[] newArray = new Object[s +
(s < (MIN_CAPACITY_INCREMENT / 2) ?
MIN_CAPACITY_INCREMENT : s >> 1)];
System.arraycopy(a, 0, newArray, 0, s);
array = a = newArray;
}
a[s] = object;
size = s + 1;
modCount++;
return true;
}

public boolean addAll(int index, Collection<? extends E> collection) {
int s = size;
if (index > s || index < 0) {
throwIndexOutOfBoundsException(index, s);
}
Object[] newPart = collection.toArray();
int newPartSize = newPart.length;
if (newPartSize == 0) {
return false;
}
Object[] a = array;
int newSize = s + newPartSize; // If add overflows, arraycopy will fail
if (newSize <= a.length) {
System.arraycopy(a, index, a, index + newPartSize, s - index);
} else {
//addAll扩容,
int newCapacity = newCapacity(newSize - 1);  // ~33% growth room
Object[] newArray = new Object[newCapacity];
System.arraycopy(a, 0, newArray, 0, index);
System.arraycopy(a, index, newArray, index + newPartSize, s-index);
array = a = newArray;
}
System.arraycopy(newPart, 0, a, index, newPartSize);
size = newSize;
modCount++;
return true;
}

//addAll使用的扩容方法,与add内嵌的算法相同。(但是,addAll传入的参数为新的元素个数-1)
//若当前的元素个数小于6,则新容量为,旧的个数+12;若当前元素个数大于6,新容量为旧的个数的1.5倍
private static int newCapacity(int currentCapacity) {
int increment = (currentCapacity < (MIN_CAPACITY_INCREMENT / 2) ?
MIN_CAPACITY_INCREMENT : currentCapacity >> 1);
return currentCapacity + increment;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  arraylist 源码