1

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

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

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

第一种方式:

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

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

4

3 回答 3

5

If you just need a set of numbers, then use HashSet and not a List. If you need to preserve the order by which you are putting the numbers, use LinkedHashSet. As for removal, always prefer the version with the iterator, even though in your particular case the performance may be comparable. The idiom with iterator is more widely applicable than indexing, for example if you used a LinkedList, indexing would result in disastrous performance.

于 2012-04-29T07:54:41.307 回答
3

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.

于 2012-04-29T07:55:29.683 回答
0

如果您需要存储重复项,我建议您使用Map<Integer,Integer>其中第一个整数是键,第二个是键出现次数。因此,当您添加已经存在的键时,您只需增加相应的计数器。(在删除操作中,您反之亦然)。当您需要所有不同的值时,您只需使用Map.keySet ()。

于 2012-04-29T07:41:02.283 回答