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

我想快速从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; }