簡體   English   中英

在Java中刪除ArrayList的最后一個對象

[英]Removing last object of ArrayList in Java

我想快速從ArrayList刪除最后一個對象。

我知道remove(Object O)ArrayList占用O(n) ,但是我想知道是否可以在恆定時間內執行此操作,因為我只想刪除最后一個對象?

請參閱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;
}

只需簡單地使用。

arraylist.remove(arraylist.size() - 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM