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



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap