整个ArrayList用的最多的就是System类提供的本地方法.
public static void arraycopy(Object src,
int srcPos, Object dest,
int destPos,
int length)
和JDK6不一样,JDK7的ArrayList构造函数,创建的是一个没有任何元素的数组.而JDK6默认创建10个元素的数组.
新增元素流程
-
public boolean add(E e) {
-
ensureCapacityInternal(size + 1);
-
elementData[size++] = e;
-
return true;
-
}
-
-
private void ensureCapacityInternal(int minCapacity) {
-
if (elementData == EMPTY_ELEMENTDATA) {
-
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
-
}
-
-
ensureExplicitCapacity(minCapacity);
-
}
-
-
private void ensureExplicitCapacity(int minCapacity) {
-
modCount++;
-
-
-
if (minCapacity - elementData.length > 0)
-
grow(minCapacity);
-
}
-
private void grow(int minCapacity) {
-
-
int oldCapacity = elementData.length;
-
int newCapacity = oldCapacity + (oldCapacity >> 1);
-
if (newCapacity - minCapacity < 0)
-
newCapacity = minCapacity;
-
if (newCapacity - MAX_ARRAY_SIZE > 0)
-
newCapacity = hugeCapacity(minCapacity);
-
-
elementData = Arrays.copyOf(elementData, newCapacity);
-
}
add之前,先保证容量.如果数组是空的,则分配10个元素.否则增长目前数组容量的一半.
其他的方法也是类似
-
public void add(int index, E element) {
-
rangeCheckForAdd(index);
-
-
ensureCapacityInternal(size + 1);
-
System.arraycopy(elementData, index, elementData, index + 1,
-
size - index);
-
elementData[index] = element;
-
size++;
-
}
-
-
public E remove(int index) {
-
rangeCheck(index);
-
-
modCount++;
-
E oldValue = elementData(index);
-
-
int numMoved = size - index - 1;
-
if (numMoved > 0)
-
System.arraycopy(elementData, index+1, elementData, index,
-
numMoved);
-
elementData[--size] = null;
-
-
return oldValue;
-
}
-
-
public boolean remove(Object o) {
-
if (o == null) {
-
for (int index = 0; index < size; index++)
-
if (elementData[index] == null) {
-
fastRemove(index);
-
return true;
-
}
-
} else {
-
for (int index = 0; index < size; index++)
-
if (o.equals(elementData[index])) {
-
fastRemove(index);
-
return true;
-
}
-
}
-
return false;
-
}
-
-
public boolean addAll(Collection<!--? extends E> c) {
-
Object[] a = c.toArray();
-
int numNew = a.length;
-
ensureCapacityInternal(size + numNew);
-
System.arraycopy(a, 0, elementData, size, numNew);
-
size += numNew;
-
return numNew != 0;
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2121444/
,如需转载,请注明出处,否则将追究法律责任。