Exception List for Exception

I wanted to check how to get the intersection between two lists, here is my code:

List<Integer> list = Arrays.asList(16, 17, 18, 19, 20); List<Integer> list2 = list.subList(2, 5); System.out.println(list.subList(2, 5)); System.out.println(list.containsAll(list.subList(2, 5))); System.out.println(list.retainAll(list2)); 

This gives:

 Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.remove(Unknown Source) at java.util.AbstractList$Itr.remove(Unknown Source) at java.util.AbstractCollection.retainAll(Unknown Source) at gov.noaa.nhc.App.main(App.java:48) 

But I do not do any deletions. Why is this a throwing exception?

Update I:

Using:

 List<Integer> list = new ArrayList<Integer>(Arrays.asList(16, 17, 18, 19, 20)); List<Integer> list2 = list.subList(2, 5); 

Produces:

 java.util.ConcurrentModificationException 

Since list2 is supported by list1, removing this item from list1 will throw this exception. Finally, the working version:

 List<Integer> list = new ArrayList<Integer>(Arrays.asList(16, 17, 18, 19, 20)); List<Integer> list2 = Arrays.asList(18, 19, 20); 

or

 List<Integer> list = new ArrayList<Integer>(Arrays.asList(16, 17, 18, 19, 20)); List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(18, 19, 20)); 

or

  List<Integer> list = new ArrayList<Integer>(Arrays.asList(16, 17, 18, 19, 20)); List<Integer> list2 = new ArrayList<Integer>(list.subList(2, 5)); 

Thanks for all your answers.

+7
source share
5 answers

When you use Arrays.asList , you get a list supported by the actual array passed with limited functions. If you want to completely change the list, you need to create a new list. For example:

 List<Integer> list = new ArrayList<Integer>(Arrays.asList(16, 17, 18, 19, 20)); List<Integer> list2 = new ArrayList<Integer>(list.subList(2, 5)); list.retainAll(list2); System.out.println(list); // result: [18, 19, 20] 
+16
source

According to the documentation , List.retainAll() method

Saves only the items in this list that are contained in the specified collection (optional operation). In other words, removes from this list all items that are not contained in the specified collection. [emphasis mine]

+3
source

retainAll removes items from the list to which it is called.

+1
source

keepAll deletes all items that are not in this list.

0
source

The documentation also says that preserveAll throws an UnsupportedOperationException when the List implementation does not support this method.

0
source

All Articles