我正在尝试将一些集合分组为不相交的集合。例如,如果我有这 5 套:
[[1, 3], [2], [1, 5], [6, 8], [1, 7]]
我想要这样的结果:
[[2], [6, 8], [1, 3, 5, 7]]
这是代码:
import java.util.*;
public class SetTest {
public static void main(String[] args) {
// ---- Initialisation
Set<Set<Integer>> groups = new LinkedHashSet<Set<Integer>>();
for (int[] set : new int[][] { {1, 3 }, {2 }, {1, 5 }, {6, 8 }, {1, 7} }) {
Set<Integer> group = new TreeSet<Integer>();
for (int i : set) {
group.add(i);
}
groups.add(group);
}
System.out.println(groups);
// ---- Grouping values in disjoint sets
for (Iterator<Set<Integer>> iterator = groups.iterator(); iterator.hasNext();) {
Set<Integer> group = iterator.next();
System.out.println(String.format(" + Checking %20s in \t %s", group, groups));
for (Set<Integer> other : groups) {
if (!group.equals(other) && !Collections.disjoint(group, other)) {
other.addAll(group);
iterator.remove();
System.out.println(String.format(" - Removed %20s -> \t %s", group, groups));
break;
}
}
}
System.out.println(groups);
}
}
我在集合上使用迭代器,我想将 2 个集合合并为一个集合,并删除其中一个。但是,我遇到了 Iterator.remove()
的问题。方法。
该程序打印的内容是:
[[1, 3], [2], [1, 5], [6, 8], [1, 7]]
+ Checking [1, 3] in [[1, 3], [2], [1, 5], [6, 8], [1, 7]]
- Removed [1, 3] -> [[2], [1, 3, 5], [6, 8], [1, 7]]
+ Checking [2] in [[2], [1, 3, 5], [6, 8], [1, 7]]
+ Checking [1, 3, 5] in [[2], [1, 3, 5], [6, 8], [1, 7]]
- Removed [1, 3, 5] -> [[2], [1, 3, 5], [6, 8], [1, 3, 5, 7]]
+ Checking [6, 8] in [[2], [1, 3, 5], [6, 8], [1, 3, 5, 7]]
+ Checking [1, 3, 5, 7] in [[2], [1, 3, 5], [6, 8], [1, 3, 5, 7]]
- Removed [1, 3, 5, 7] -> [[2], [1, 3, 5, 7], [6, 8], [1, 3, 5, 7]]
[[2], [1, 3, 5, 7], [6, 8], [1, 3, 5, 7]]
第一次,删除 [1, 3]
按预期工作,但其余时间,它不会删除该项目。我认为这是因为我使用了 addAll()
,但这是为什么呢?因为我没有在groups
中进行更改;我只更改其中的一个元素(other
) - 并且引用是相同的,对吧?
最佳答案
HashSet
的元素应该具有稳定的 hashCode
,但是当您迭代外部集合时,您会改变它们。这会以不可预测但有记录的方式失败。
在 TreeSet
中,通过突变更改元素的排序顺序也可能会出现问题。
关于java - 迭代器的删除方法在第一次调用后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11226798/