ArrayList.clear() 和 ArrayList.removeAll() 有什么区别?

编程入门 行业动态 更新时间:2024-10-26 02:35:41
本文介绍了ArrayList.clear() 和 ArrayList.removeAll() 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

假设 arraylist 被定义为 ArrayList;arraylist,是 arraylist.removeAll(arraylist) 等价于 arraylist.clear()?

Assuming that arraylist is defined as ArrayList<String> arraylist, is arraylist.removeAll(arraylist) equivalent to arraylist.clear()?

如果是这样,我可以假设 clear() 方法更有效地清空数组列表吗?

If so, can I assume that the clear() method is more efficient for emptying the array list?

使用arraylist.removeAll(arraylist)代替arraylist.clear()有什么注意事项吗?

Are there any caveats in using arraylist.removeAll(arraylist) instead of arraylist.clear()?

推荐答案

clear()的源码:

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

removeAll()的源代码(在AbstractCollection中定义):

The source code for removeAll()(As defined in AbstractCollection):

public boolean removeAll(Collection<?> c) {
    boolean modified = false;
    Iterator<?> e = iterator();
    while (e.hasNext()) {
        if (c.contains(e.next())) {
            e.remove();
            modified = true;
        }
    }
    return modified;
}

clear() 快得多,因为它不必处理所有这些额外的方法调用.

clear() is much faster since it doesn't have to deal with all those extra method calls.

正如 Atrey 指出的那样,c.contains(..)removeAll 的时间复杂度增加到 O(n2) 作为与 clear 的 O(n) 相反.

And as Atrey points out, c.contains(..) increases the time complexity of removeAll to O(n2) as opposed to clear's O(n).

这篇关于ArrayList.clear() 和 ArrayList.removeAll() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 11:57:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/885807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   ArrayList   clear   removeAll

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!