我想快速从 ArrayList
中删除最后一个对象。
我知道 remove(Object O)
在 ArrayList
中采用 O(n)
,但我想知道是否可以这样做因为我只想删除 last 对象,所以这是恒定的时间?
最佳答案
见 the documentation for ArrayList#remove(int)
, 语法如下:
list.remove(list.size() - 1)
这是它的实现方式。 elementData
对后备数组进行查找(因此它可以将其从数组中删除),这应该是恒定时间(因为 JVM 知道对象引用的大小以及它可以计算偏移量),对于这种情况,numMoved
是 0
:
public E remove(int index) {
rangeCheck(index); // throws an exception if out of bounds
modCount++; // each time a structural change happens
// used for ConcurrentModificationExceptions
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;
}
关于java - 在 Java 中删除 ArrayList 的最后一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16987727/