如何迭代和修改 Java 集? [英] How do I iterate and modify Java Sets?

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

问题描述

假设我有一个整数集,我想递增集合中的每个整数.我该怎么做?

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 对象是不可变的;我的策略是遍历集合,对于每个整数 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 集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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