59

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

I know that remove(Object O) takes O(n) in an ArrayList, but I wonder if it is possible to do this in constant time since I just want to remove the last object?

13
  • 32
    list.remove(list.size()-1) !!! Commented Jun 7, 2013 at 15:29
  • 2
    Would a stack be a better solution here? Commented Jun 7, 2013 at 15:30
  • 6
    Removing the last element is a constant time operation since no elements needed to be shifted to the left Commented Jun 7, 2013 at 15:31
  • 2
    @TheNewIdiot You should have posted that as an answer... D: Commented Jun 7, 2013 at 15:47
  • 1
    @thegrinner: "big-o" != "worst-case". Commented Jun 7, 2013 at 16:02

2 Answers 2

97

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

O1 for this? arraycopy entire up to, or just cutting the array loose from end ?
10

Since Java 21, simply using List.removeLast, for example:

List<Integer> list = new ArrayList<>(List.of(1, 2, 3));

System.out.println(list.removeLast()); // 3 - removes and returns the last element

Note: if the list is not empty, the implementation of List.removeLast returns the result of calling remove(size() - 1). Otherwise, it throws NoSuchElementException.

The time complexity of removing the last element from ArrayList is O(1) - it is just decrementing the size of the list by 1 under the hood.

1 Comment

Wow, it took them 30 years to add something other languages had from day 1. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.