如何迭代和修改Java集

如何迭代和修改Java集

本文介绍了如何迭代和修改Java集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一组整数,我想增加Set中的每个Integer。我该怎么做?

Let's say I have a Set of Integers, and I want to increment every Integer in the Set. How would I do this?

我是否允许在迭代时添加和删除集合中的元素?

Am I allowed to add and remove elements from the set while iterating it?

我是否需要创建一个新的集合,我将复制和修改元素,而我正在迭代原始集合?

Would I need to create a new set that I would "copy and modify" the elements into, while I'm iterating the original set?

编辑:如果集合的元素是不可变的吗?

What if the elements of the set are immutable?

推荐答案

您可以在迭代期间使用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);

这篇关于如何迭代和修改Java集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:30