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

查看:59
本文介绍了在 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 知道对象引用的大小以及它可以使用的条目数)计算偏移量),对于这种情况,numMoved0:

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天全站免登陆