在Java中删除ArrayList的最后一个对象 [英] Removing last object of ArrayList in Java

查看:132
本文介绍了在Java中删除ArrayList的最后一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想快速从 ArrayList 中删除​​最后一个对象。

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

我知道 remove(Object O) ArrayList 中获取 O(n),但是我想知道是否有可能在恒定时间内完成此操作,因为我只想删除最后对象?

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?

推荐答案

请参阅文档对于 ArrayList #remove(int) ,如以下语法:

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

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

这是怎么回事实现。 elementData 对后备数组进行查找(因此可以将其从数组中删除),这应该是常量时间(因为JVM知道对象引用的大小和它可以计算偏移的条目数), numMoved 对于这种情况是 0

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;
}

这篇关于在Java中删除ArrayList的最后一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆