Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList retainAll confusing me

Tags:

java

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?

like image 645
Oliver Watkins Avatar asked Apr 10 '26 04:04

Oliver Watkins


1 Answers

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:

[]

like image 114
OldCurmudgeon Avatar answered Apr 11 '26 18:04

OldCurmudgeon