且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何迭代和修改Java集?

更新时间:2022-06-17 00:43:47

您可以在迭代期间使用Iterator对象安全地从集合中删除;尝试在迭代时通过其API修改集合将破坏迭代器。 Set类通过getIterator()提供一个迭代器。

You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().

但是,Integer对象是不可变的;我的策略是遍历集合,对于每个Integer i,将i + 1添加到一些新的临时集合中。完成迭代后,从原始集中删除所有元素并添加新临时集的所有元素。

however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.

Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
    temp.add(i+1);
s.clear();
s.addAll(temp);