从数组列表中删除元素的更有效方法 [英] More efficient way to remove elements from an array list

查看:29
本文介绍了从数组列表中删除元素的更有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个类似这样的数组列表

I have developed a array list something like this

ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("8");
list.add("8");
list.add("3");
list.add("4");

现在我的问题是:如果我想从列表中删除8",哪种方式更好?

Now my question is: if I want to remove the "8"s from the list, which way is better?

第一种方式:

for(int i = 0; i < list.size(); i++) {
    if(list.get(i).equals("8")) {
        list.remove(i);
        i--;
    }
}

第二种方式:

Iterator<String> iterator = list.iterator();
    while(iterator.hasNext())
        if(iterator.next().equals("8"))
            iterator.remove();

现在请告知从性能的角度来看,其中哪一个更有效、更快,还有没有其他方法可以通过使用内置函数来删除重复项而无需进行太多迭代.

Now please advise which one of them is more efficient and faster from performance point of view and also is there any other way that is something like built in function by using it we can remove duplicate without iterating that much.

推荐答案

性能方面它们应该相似.你测试过吗?如果你想使用内置方法,你可以用类似的性能来做到这一点.(有待测试确认):

Performance wise they should be similar. Have you tested? If you want to use the built in methods, you can do this with a similar performance.(to be confirmed by testing):

list.removeAll(Arrays.asList("8"));

最后,如果您想要一个没有重复的列表,请使用其他人提到的 Set.

Finally if you want a list without duplicates, use a Set as others have mentioned.

这篇关于从数组列表中删除元素的更有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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