Com.google.common.collect.Sets.SetView error or function?

Hi, I have 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); } 

and he throws

 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) 

- this is normal? or a small mistake ...

+4
source share
1 answer

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

The unmodifiable form of a set, which can be supported by other sets; this view will change as the stand sets do.

So, when you call set1.removeAll(x) and go into the view, you are essentially trying to remove from set1 during a loop over a part of yourself. This is the cause of the ConcurrentModificationException .

To achieve what you are trying to do, see SetView.immutableCopy() .

For instance:

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

Source: https://habr.com/ru/post/1386121/


All Articles