在Java中删除ArrayList的最后一个对象

Ari*_*deh 36 java arraylist data-structures

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

我知道remove(Object O)接受O(n)一个ArrayList,但我想知道是否有可能在恒定时间内这样做,因为我只想删除最后一个对象?

Nat*_*hes 69

请参阅以下语法中的文档ArrayList#remove(int):

list.remove(list.size() - 1)
Run Code Online (Sandbox Code Playgroud)

以下是它的实现方式.elementData确实背衬阵列上的查找(因此它可以切断它从阵列疏松的),这应该是恒定的时间(因为JVM知道一个对象引用的大小,它可以计算偏移量的条目的数量),并且numMoved0用于这个案例:

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;
}
Run Code Online (Sandbox Code Playgroud)