更有效的方法从数组中删除列表中的元素

问题描述:

我开发了一个数组列表,像这样

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");

现在我的问题是:如果我想从列表中,哪种方式更好去掉8S

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"));

最后,如果你想在不重复的列表,使用一组如其他人提及。

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