[英]Arraylist IndexOutOfBoundsException after removing element
[英]What is the result after removing an element in the middle of an ArrayList?
当我们从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;
}
从这里 :
public E remove(int index)
:删除此列表中指定位置的元素。 将所有后续元素向左移动(从其索引中减去一个)。
当您尝试从arrayList
方法中删除一个元素时,剩余的条目将向后移动,因此没有间隙。
删除此列表中指定位置的元素(可选操作)。 将所有后续元素向左移动(从其索引中减去一个)。 返回从列表中删除的元素。
谢谢
将使用旧元素创建新列表,或者将其后的元素移到旧列表的左侧
不,因为ArrayList
是可变的。 删除元素时,这会影响当前的ArrayList
对象引用,该引用将少一个元素。 被删除的元素之后的元素将向左移动。
加。 到Javadoc ,它将元素向左移动。 看一看
您要删除的元素之后的元素将向左移动。 数组列表元素将被重新排列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.