Removing last object of ArrayList in Java

后端 未结 2 1697
旧时难觅i
旧时难觅i 2021-02-02 06:49

I want to remove the last object from an ArrayList quickly.

I know that remove(Object O) takes O(n) in an ArrayList,

相关标签:
2条回答
  • 2021-02-02 07:12

    See the documentation for ArrayList#remove(int), as in the following syntax:

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

    Here is how it's implemented. elementData does a lookup on the backing array (so it can cut it loose from the array), which should be constant time (since the JVM knows the size of an object reference and the number of entries it can calculate the offset), and numMoved is 0 for this case:

    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;
    }
    
    0 讨论(0)
  • 2021-02-02 07:23

    Just simply use.

    arraylist.remove(arraylist.size() - 1)
    
    0 讨论(0)
提交回复
热议问题