2013-06-07 10 views
27

ArrayListから最後のオブジェクトをすばやく削除したいと考えています。JavaでArrayListの最後のオブジェクトを削除する

私はremove(Object O)ArrayListO(n)がかかりますが、私はちょうど最後オブジェクトを削除したいので、一定の時間でこれを行うことが可能である場合、私は疑問に思うことを知っていますか?

+0

'(int型)' ... ' –

+18

list.removeを削除もあります' !!! – NINCOMPOOP

+2

スタックはここでより良い解決策になりますか? –

答えて

52

は、次の構文のように、the documentation for ArrayList#remove(int)を参照してください:ここで

list.remove(list.size() - 1) 

は、それが実装されています方法です。 elementDataは、(JVMがオブジェクト参照のサイズとオフセットを計算できるエントリの数を知っているので)一定の時間になるはずのバッキング配列のルックアップを行います(配列から緩やかに切断できます)。numMovedこの場合の0されています(はlist.size() - 1)

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; 
} 
関連する問題