gpt4 book ai didi

java - com.google.common.collect.Sets.SetView 错误或功能?

转载 作者:搜寻专家 更新时间:2023-10-31 19:30:02 24 4
gpt4 key购买 nike

你好,我有这段代码:

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)

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

最佳答案

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

An unmodifiable view of a set which may be backed by other sets; this view will change as the backing sets do.

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

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

例如:

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

关于java - com.google.common.collect.Sets.SetView 错误或功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8490901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com