当我们从ArrayList
中间删除一个元素时,结果是什么:将创建一个包含旧元素的新列表,或者后面的元素将在旧列表中向左移动?
最佳答案
当您从 ArrayList
中删除一个元素时,被删除元素后面的所有元素的索引都会减 1。
ArrayList
由数组支持。在删除的情况下,被删除元素后面的后备数组部分将被复制到从被删除元素索引开始的数组部分。这是通过 System.arraycopy 完成的:
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
// this is the part that moves the following elements
System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null;
return oldValue;
}
关于java - 删除ArrayList中间的元素后结果是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33056466/