JDK里的java.util.Vector类,其方法removeElementAt的代码如下:
public synchronized void removeElementAt(int index) {
modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
最后的代码是
elementData[elementCount] = null; /* to let gc do its work */
把remove掉的element的引用,设置为了null,这样,就能防止内存泄露了,否则可能会报错OutOfMemoryError。