Fix: java.lang.UnsupportedOperationException Java Collections (List, Set, Map)

Example 1: ArrayList
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);

    }

}

Exception in thread "main" java.lang.UnsupportedOperationException
     at java.base/java.util.AbstractList.add(AbstractList.java:155)
     at java.base/java.util.AbstractList.add(AbstractList.java:113)
     at org.code2care.generics.ClassCastExceptionExample.main(UnsupportedOperationExceptionExample1.java:13)

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.

java.lang.UnsupportedOperationException

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
    
        }
    
    }

    Comments & Discussion

    Facing issues? Have questions? Post them here! We're happy to help!