privatevoidgrow(int minCapacity){ // overflow-conscious code int oldCapacity = elementData.length; //先扩容0.5倍,新数组容量为旧数组容量的1.5倍,此处newCapacity可能为负值 int newCapacity = oldCapacity + (oldCapacity >> 1); //若新数组容量仍然小于所需最小容量,则新容量设为所需最小容量 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //如果新容量大于最大数组容量时,新容量设为最大尺寸 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: //调用System.arraycopy,这是一个native方法,使用内存复制 elementData = Arrays.copyOf(elementData, newCapacity); }
privatevoidrangeCheck(int index){ if (index >= size) thrownew IndexOutOfBoundsException(outOfBoundsMsg(index)); } E elementData(int index){ return (E) elementData[index]; }
set方法
1 2 3 4 5 6 7
public E set(int index, E element){ rangeCheck(index);
E oldValue = elementData(index); elementData[index] = element; return oldValue; }
remove方法
根据索引来删除数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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; // clear to let GC do its work
publicbooleanremove(Object o){ if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }
//和remove方法区别在于不检验index的合法性,无返回值这里index由for循环产生,//一定是合法的 privatevoidfastRemove(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 }
privatebooleanbatchRemove(Collection<?> c, boolean complement){ final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }