package org.code2care.exceptions;
import java.util.Arrays;
import java.util.List;
public class UnsupportedOperationExceptionExample1 {
public static void main(String[] args) {
List<String> nameList = Arrays.asList("Sam", "Alex", "Mike", "Annie", "Jane");
nameList.add("Andrew");
}
}
Example 2: LinkedList
public class UnsupportedOperationExceptionExample2 {
public static void main(String[] args) {
List<String> nameList = LinkedList.of("Sam", "Alex", "Mike", "Annie", "Jane");
nameList.add("Andrew");
}
}
Example 3: Set - HashSet
public class UnsupportedOperationExceptionExample3 {
public static void main(String[] args) {
Set<Integer> numbers = Set.of(10,20,30,40,50);
numbers.add(44);
}
}
All the three above examples will give java.lang.UnsupportedOperationException because when you make use of Arrays.asList() or the Collection.of() methods you get an immutable collection, thus you cannot modify such collection by adding, deleting our updating it.

Fix: java.lang.UnsupportedOperationException
The fix is simple, just create the collection as you do use the new keyword and add elements using the add method(s).
Example:public class FixUnsupportedOperationException {
public static void main(String[] args) {
List<String> nameList = new ArrayList();
nameList.add("Sam");
nameList.add("Alex");
nameList.add("Mike");
nameList.add("Annie");
nameList.add("Jane");
nameList.add("Andrew"); //No issue
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!