ArrayList对于两个相同的数字如何删除?

首先是ArrayList.remove(Object o)的源码:

  1. public boolean remove(Object o) {
  2. if (o == null) {
  3. for (int index = 0; index < size; index++)
  4. if (elementData[index] == null) {
  5. fastRemove(index);
  6. return true;
  7. }
  8. } else {
  9. for (int index = 0; index < size; index++)
  10. if (o.equals(elementData[index])) {
  11. fastRemove(index);
  12. return true;
  13. }
  14. }
  15. return false;
  16. }

可见当o != null的时候,会去从头开始遍历,并删除匹配到的第一个元素,然后直接返回。
其中fastRemove的源码为:

  1. /*
  2. * Private remove method that skips bounds checking and does not
  3. * return the value removed.
  4. */
  5. private void fastRemove(int index) {
  6. // 操作计数器加一
  7. modCount++;
  8. // 要移动的元素数量
  9. int numMoved = size - index - 1;
  10. // 如果要移动的元素数量大于0
  11. if (numMoved > 0)
  12. // 将被删除元素之后的元素,全部向前移动一位
  13. System.arraycopy(elementData, index+1, elementData, index,
  14. numMoved);
  15. // 将size减一,然后把缩减前的最后一个元素所在位置的引用置为空(减少对象的引用),以让JVM执行GC将其回收
  16. elementData[--size] = null; // clear to let GC do its work
  17. }

该方法跳过边界检查且不会返回删除的值。