45

我想快速删除最后一个对象ArrayList

我知道这remove(Object O)需要O(n)一个ArrayList,但我想知道是否可以在恒定时间内执行此操作,因为我只想删除最后一个对象?

4

2 回答 2

83

请参阅的文档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;
}
于 2013-06-07T15:29:31.430 回答
0

只需简单地使用。

arraylist.remove(arraylist.size() - 1)
于 2019-01-24T09:25:20.783 回答