Java ArrayList - 删除元素,向下移动列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18688339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ArrayList - remove element, shifting list down?
提问by Nicolas Mustaro
This is a pretty straight-forward question... Just couldn't really find a straight-forward answer on the web.
这是一个非常直截了当的问题......只是无法在网上找到一个直截了当的答案。
Consider I have a List<String> listOfStrings = new ArrayList();
and it is populated with 20 values.
考虑我有一个List<String> listOfStrings = new ArrayList();
,它填充了 20 个值。
If listOfStings.get(0) = zero
, listOfStrings.get(1) = one
, etc...
如果listOfStings.get(0) = zero
, listOfStrings.get(1) = one
, 等等...
and I do listOfStrings.remove(0)
我做 listOfStrings.remove(0)
would listOfStrings.get(0)
become null
, or would the elements shift down so
listOfStrings.get(0)
becomes one
?
会listOfStrings.get(0)
变成null
,还是元素会向下移动
listOfStrings.get(0)
变成one
?
回答by Oleg Pyzhcov
As specified in List interface documentation, it will be shifted to the left.
按照List interface documentation 中的规定,它将向左移动。
回答by Sotirios Delimanolis
The implementation of ArrayList#remove(E)
is as follows
的实现ArrayList#remove(E)
如下
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);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
Where elementData
is the backing element array.
elementData
支持元素数组在哪里。
In words, it's not so much a shift, as it is a copy of elements, minus the element missing.
换句话说,它不是一个转变,因为它是元素的副本,减去缺少的元素。
Given elementData
with 10 elemetns
给定elementData
10 个元素
[ 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10]
^ index 4
removing elements at index 4 would do
删除索引 4 处的元素会做
// copy elements starting from index+1
[ 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10]
^ index+1
// to the same array starting at index
[ 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10]
^ index
// resulting in
[ 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 | 10 | null ]
get(4)
would then return value (6)`.
get(4)
然后将返回值 (6)`。
The List
api states
该List
API状态
Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
移除此列表中指定位置的元素(可选操作)。将任何后续元素向左移动(从它们的索引中减去一个)。返回从列表中删除的元素。
How that is implemented is up to the implementor. The above is just ArrayList
's implementation.
如何实现取决于实现者。以上只是ArrayList
的实现。