I am trying to work with intersections in java. If I have the following, i just want an arraylist with nothing in it because the intersection gives me zero.
List<String> coll1 = Arrays.asList(["A"]);
List<String> coll2 = Arrays.asList(["B","C"]);
coll1.retainAll(coll2);
However retainAll throws this exception :
java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at java.util.AbstractList$Itr.remove(AbstractList.java:374)
at java.util.AbstractCollection.retainAll(AbstractCollection.java:410)
If I convert the lists to sets, then I get a set which is empty if I call retainAll :
Set<String> set1 = new HashSet<String>(coll1);
Set<String> set2 = new HashSet<String>(coll2);
set1.retainAll(set2); //gives me an empty set, which is good!
Why does ArrayList have a problem with empty intersections?
This is because Arrays.asList creates an immutable list so when you call retainAll which tries to remove entries from the list it complains.
The solution is to create a new ArrayList copy of it.
public void test(String[] args) {
List<String> coll1 = new ArrayList<>(Arrays.asList("A"));
List<String> coll2 = new ArrayList<>(Arrays.asList("B","C"));
coll1.retainAll(coll2);
System.out.println(coll1);
}
prints:
[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With