Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsupportedOperationException - the removeAll method is not supported by this collection (Java Collections)

Set<Badge> availableBadges = myService.getAvailableBadges();
List<Badge> allBadges = Arrays.asList(Badge.values());
allBadges.removeAll(availableBadges);
/* Badge is an enumn */

what collections do support remove all ?

like image 219
NimChimpsky Avatar asked Jan 07 '13 17:01

NimChimpsky


People also ask

How do I resolve UnsupportedOperationException in Java?

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList , which can be modified. An unmodifiable collection or data structure should not be attempted to be modified.

How do you write a removeAll method in Java?

The Java ArrayList removeAll() method removes all the elements from the arraylist that are also present in the specified collection. The syntax of the removeAll() method is: arraylist. removeAll(Collection c);


2 Answers

Arrays.asList returns a partially unmodifiable implementation (in part of remove* methods - thanks to @LouisWasserman for the remark) of the List interface.

EDIT 1: Use an ArrayList wrapper on it: new ArrayList<Badge>(allBadges);

like image 90
Andremoniy Avatar answered Oct 27 '22 01:10

Andremoniy


Your collection might be unmodifiable.

You need to create new List

List<T> list = new ArrayList<>(unmodifiableList);

Now your list is modifiable and you can perform remove and removeAll operations.

like image 39
T.Thakkar Avatar answered Oct 27 '22 02:10

T.Thakkar