[英]Removing last object of ArrayList in Java
I want to remove the last object from an ArrayList
quickly. 我想快速从
ArrayList
删除最后一个对象。
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? 我知道
remove(Object O)
在ArrayList
占用O(n)
,但是我想知道是否可以在恒定时间内执行此操作,因为我只想删除最后一个对象?
See the documentation for ArrayList#remove(int)
, as in the following syntax: 请参阅
ArrayList#remove(int)
的文档 ,如以下语法所示:
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: 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.