com.google.common.collect.Sets.SetView错误或功能? [英] com.google.common.collect.Sets.SetView bug or feature?

查看:2800
本文介绍了com.google.common.collect.Sets.SetView错误或功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello我有这段代码:

Hello I've this piece of code:

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)

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

is this a normal? or a small bug...

推荐答案

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

SetView is a view of the intersection of these sets, not a copy. From the Guava docs:


集合的不可修改视图,可以由其他集合支持;

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)
并传入视图,你基本上试图从循环它自身的一部分时删除 set1 。这是 ConcurrentModificationException的原因

So, when you call set1.removeAll(x) and pass in the view, you're essentially trying to remove from set1 while looping over part of itself. This is the reason for the ConcurrentModificationException.

要实现您想要做的事,请查看 SetView.immutableCopy( )

To achieve what you're trying to do, have a look at SetView.immutableCopy().

例如:

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

这篇关于com.google.common.collect.Sets.SetView错误或功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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