ArrayList.clear() 和 ArrayList.removeAll() 有什么区别? [英] What is the difference between ArrayList.clear() and ArrayList.removeAll()?

查看:42
本文介绍了ArrayList.clear() 和 ArrayList.removeAll() 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 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屋!

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