// 这个也是空数组,用来初始化的,它与上面的空数组的不同在源码中解释如下 // We distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when first // element is added. // 我们将此与EMPTY_ELEMENTDATA区别开来,以了解添加第一个元素时要充气多少。 privatestaticfinal Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 通过下标移除元素 public E remove(int index){ if (index >= size) thrownew IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++; // 拿到旧元素 E oldValue = (E) elementData[index]; // 移除元素过后数组需要移动距离,size - index - 1,就是 index 后面所有的元素 int numMoved = size - index - 1; if (numMoved > 0) // 这个方法上面已经说过,在这里呢,主要是将数组后 numMoved 个元素向前移一位 System.arraycopy(elementData, index+1, elementData, index, numMoved); // 将 index 为 size -1 的元素也就是最后一个元素置为空,并且元素个数减一 elementData[--size] = null; // clear to let GC do its work // 返回旧元素 return oldValue; }
// 通过元素移除移除元素,返回是否操作成功 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; }
那么快速移除是怎么具体实现呢?
1 2 3 4 5 6 7 8 9
// 我们可以看到,fastRemove() 方法与第一个 remove() 方法差不多一样的 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 }
近期评论