我想快速删除最后一个对象ArrayList
。
我知道这remove(Object O)
需要O(n)
个ArrayList
,但是我想知道是否可以在恒定时间内执行此操作,因为我只想删除最后一个对象?
请参阅的文档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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句