1

我正在尝试将一些集合分组为不相交的集合。例如,如果我有这 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)——而且引用是一样的,对吧?

4

1 回答 1

2

a 的一个元素HashSet应该有一个 stable hashCode,但是当你迭代外部集合时,你正在改变它们。这以不可预测但记录在案的方式失败了。

在 aTreeSet中,通过突变改变元素的排序顺序也可能存在问题。

于 2012-06-27T13:13:54.243 回答