【问题标题】:com.google.common.collect.Sets.SetView bug or feature?com.google.common.collect.Sets.SetView 错误或功能?
【发布时间】:2011-12-13 14:32:23
【问题描述】:

你好,我有这段代码:

public static void main(String[] args) {
    Set<Integer> set1 = new HashSet<Integer>();
    Set<Integer> set2 = new HashSet<Integer>();
    set1.add(1);
    set1.add(2);
    set1.add(3);
    set1.add(4);
    set1.add(5);

    set2.add(4);
    set2.add(5);
    set2.add(6);
    set2.add(7);
    set2.add(8);

    SetView<Integer> x = Sets.intersection(set1, set2);
    set1.removeAll(x);
    set2.removeAll(x);
}

它会抛出

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:841)
    at java.util.HashMap$KeyIterator.next(HashMap.java:877)
    at com.google.common.collect.Iterators$7.computeNext(Iterators.java:627)
    at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:141)
    at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:136)
    at java.util.AbstractSet.removeAll(AbstractSet.java:142)
    at com.Main2.main(Main2.java:30)

这是正常的吗?或者一个小错误...

【问题讨论】:

    标签: java collections guava


    【解决方案1】:

    SetView 是这些集合的交集的视图,而不是副本。来自 Guava 文档:

    可以由其他集合支持的集合的不可修改视图;这个 视图将随着支持集的变化而变化。

    因此,当您调用set1.removeAll(x) 并传入视图时,您实际上是在尝试从set1 中删除,同时循环其自身的一部分。这就是ConcurrentModificationException 的原因。

    要实现您的目标,请查看SetView.immutableCopy()

    例如:

    SetView<Integer> intersectionView = Sets.intersection(set1, set2);
    ImmutableSet<Integer> intersectionCopy = intersectionView.immutableCopy();
    set1.removeAll(intersectionCopy);
    set2.removeAll(intersectionCopy);
    

    【讨论】:

    • 听起来不错;但是如果我执行 immutableCopy(),我会从视图中删除我的对象吗?这样我就不能从我的 2 个集合中删除所有...做 new HashSet(SetView) 会更好吗?
    • 非常感谢;我正在这样做: set1.removeAll(x.immutableCopy()); set2.removeAll(x.immutableCopy());感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多