在我的数据结构类别中,我们研究了Java ArrayList阶级,以及当用户增加更多内容时,它如何发展基础阵列。 这一点得到了理解。 然而,我无法指出,当从名单上删除许多内容时,这一类别如何节省记忆。 审视来文方,有三种方法删除了内容:
public E remove(int index) {
RangeCheck(index);
modCount++;
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}
其中没有一个减少数据储存阵列。 我甚至开始问,如果记忆已经消失,但经验测试表明,它确实如此。 因此,必须采取其他办法,但在哪里和如何? 我检查了家长班子,但没有成功。