Java中ArrayList的相关问题?GC回收问题?


public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!  add操作涉及到容器的扩容
    elementData[size++] = e;//正常操作,多线程时不安全
    return true;
}

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);//把数组index之后的元素向前移1。
    elementData[--size] = null; // clear to let GC do its work

    return oldValue;
}

elementData[--size] = null; // clear to let GC do its work
那么和我直接add(null) elementData[size++] = e;这句话有什么区别?

做完16-17行的操作,第index个元素不在elementData中了,但是在elementData的末尾多出来一个元素,他和到数第二个元素是重复的;而且在ArrayList对象中再也访问不到, 但是实际上有一个引用指向它,导致在ArrayList不能回收的情况,它也不能回收。因此第18行代码就是让ArrayList中的elementData不再指向它,就可以在Arraylist回收之前回收了。
add(null) elementData[size++] = e,是在末尾添加一个空元素,和18的代码含义不一样

elementData[--size] = null; 是为了让GC清理。你这句话是相当于添加一个null元素