Java lang UnsupportedOperationException at java util AbstractList remove AbstractList java 161

一、Arrays.asList()

public class ListDemo { public static void main(String[] args) { String[] split = "abc,bcd,cde,def".split(","); List<String> list = Arrays.asList(split); //list.add("ggg"); list.remove("abc"); System.out.println(list); } }

Convert the array to a list through Arrays.asList(), the list can only be checked and modified, and the following exceptions will be thrown when adding and deleting operations:

Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.remove(AbstractList.java:161) at java.util.AbstractList$Itr.remove(AbstractList.java:374) at java.util.AbstractCollection.remove(AbstractCollection.java:293) at com.lzw.demo6.ListDemo.main(ListDemo.java:12)

 We can analyze the source code:

Java lang UnsupportedOperationException at java util AbstractList remove AbstractList java 161

 This method returns the Arrays class inside a static inner classes java.util.Arrays.ArrayList,useless rewrite add, removemethod, and therefore will throw an exception when you call the add method.

Second, through the tool class Collections.addAll()

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ListDemo2 { public static void main(String[] args) { String[] split = "abc,bcd,cde,def".split(","); List< String> list = new ArrayList<String>(split.length); Collections.addAll(list,split); list.add("ggg"); list.remove("abc"); System.out.println(list); } } [bcd, cde, def, ggg]

This method is the most efficient. It is converted by Collections.addAll(arrayList, strArray), a List of the same length is created according to the length of the array, and then the elements in the array are converted to binary by the Collections.addAll() method, and then added to List. It can be used when the amount of list data is large, which can increase efficiency.

Third, java.util.ArrayListthe constructor used

package com.lzw.demo6; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListDemo3 { public static void main(String[] args) { String[] split = "abc,bcd,cde,def".split(","); List<String> list = new ArrayList<>(Arrays.asList(split)); list.add("ggg"); list.remove("abc"); System.out.println(list); } }

This method can add, delete, and check when the amount of data is small, but it is not efficient when the amount of data is large.

The UnsupportedOperationException is one of the common exceptions that occur when we are working with some API of list implementation. It is thrown to indicate that the requested operation is not supported.

This class is a member of the Java Collections Framework.

All java errors implement the java.lang.Throwable interface or are inherited from another class. The hierarchy of this Exception is-

  java.lang.Object

         java.lang.Throwable



                   java.lang.Exception

                          java.lang.RuntimeException

                                  java.lang.UnsupportedOperationException

Syntax:

public class UnsupportedOperationException extends RuntimeException

The main reason behind the occurrence of this error is the asList method of java.util.Arrays class returns an object of an ArrayList which is nested inside the class java.util.Arrays. ArrayList extends java.util.AbstractList and it does not implement add or remove method. Thus when this method is called on the list object, it calls to add or remove method of AbstractList class which throws this exception. Moreover, the list returned by the asList method is a fixed-size list therefore it cannot be modified.

The below example will result in UnsupportedOperationException as it is trying to add a new element to a fixed-size list object

    public static void main(String[] args)

        String str[] = { "Apple", "Banana" };

        List<String> l = Arrays.asList(str);

Output:

Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.AbstractList.add(AbstractList.java:153) at java.base/java.util.AbstractList.add(AbstractList.java:111) at Example.main(Example.java:14)

We can solve this problem by using a mutable List that can be modified such as an ArrayList. We create a List using Arrays.asList method as we were using earlier and pass that resultant List to create a new ArrayList object. 

import java.util.ArrayList;

    public static void main(String[] args) {

        String str[] = { "Apple", "Banana" };

        List<String> list = Arrays.asList(str); 

        List<String> l = new ArrayList<>(list);

Output Apple Banana Mango


Article Tags :

This example shows the possible causes of java.lang.UnsupportedOperationException. This example also shows how to fix or resolve java.lang.UnsupportedOperationException.

What is java.lang.UnsupportedOperationException?

java.lang.UnsupportedOperationException is thrown to denote that the requested operation is not supported by the underlying collection object.

Possible causes and resolutions of the java.lang.UnsupportedOperationException

1) Trying to add or remove elements from the unmodifiable list object

The List  object returned by the asList method of the Arrays class is unmodifiable. That is, you cannot change the list object structurally once it is created. Trying to add or remove elements from such a list will throw the UnsupportedOperationException exception.

The Arrays#List creates a wrapper around the original array and creates a fixed-size list that cannot be modified. Thus, add and remove operations are not supported on such List object.

String[] strArray = {"Sun", "Mon", "Tue"};        

//fixed size unmodifiable list

List list = Arrays.asList(strArray);

    //add operation is not supported

}catch(UnsupportedOperationException uoe){

    System.out.println("Add operation is not supported");

    //remove operation is not supported

}catch(UnsupportedOperationException uoe){

    System.out.println("Remove operation is not supported");

Output

Add operation is not supported

java.lang.UnsupportedOperationException

    at java.util.AbstractList.add(Unknown Source)

    at java.util.AbstractList.add(Unknown Source)

    at com.javacodeexamples.exceptionexamples.UnsupportedExceptionExample.main(UnsupportedExceptionExample.java:16)

Remove operation is not supported

java.lang.UnsupportedOperationException

    at java.util.AbstractList.remove(Unknown Source)

    at com.javacodeexamples.exceptionexamples.UnsupportedExceptionExample.main(UnsupportedExceptionExample.java:25)

Fix/Resolution

Convert list object returned by the asList method to an ArrayList before adding or removing elements from it like given below.

String[] strArray = {"Sun", "Mon", "Tue"};        

//fixed-size unmodifiable list

List list = Arrays.asList(strArray);

//convert fixed size list to an ArrayList

list = new ArrayList(list);

System.out.println("List is modified");

2) Trying to remove elements using an Iterator

Theremove method of an Iterator class may throw the UnsupportedOperationException if the iterator is obtained from an unmodifiable List object (like given in the above example) and the remove method is called while iterating over the list.

String[] strArray = {"Sun", "Mon", "Tue"};        

//fixed size unmodifiable list

List list = Arrays.asList(strArray);

Iterator itrList = list.iterator();

while(itrList.hasNext()){

    if( itrList.next().equals("Mon") ){

        //remove operation is not supported

Output

Exception in thread "main" java.lang.UnsupportedOperationException

    at java.util.AbstractList.remove(Unknown Source)

    at java.util.AbstractList$Itr.remove(Unknown Source)

    at com.javacodeexamples.exceptionexamples.UnsupportedExceptionExample.main(UnsupportedExceptionExample.java:50)

Fix/Resolution

Create a new ArrayList or LinkedList object from the list before iterating and removing elements from the Iterator or List.

//create new ArrayList from fixed size list object

list = new ArrayList<String>(list);

Iterator<String> itrList = list.iterator();        

while(itrList.hasNext()){

    if( itrList.next().equals("Mon") ){

3) Trying to add, remove or set elements using ListIterator

Theadd, set, andremove methods of the ListIterator may throw UnsupportedOperationException if the ListIterator is obtained from a fixed-size List object and any of these methods are called while iterating over such a list.

String[] strArray = {"Sun", "Mon", "Tue"};        

//fix sized unmodifiable list

List list = Arrays.asList(strArray);

ListIterator listItr = list.listIterator();

    //Remove is not supported

Fix/Resolution

Create a new ArrayList object from the fixed size list and get the ListIterator from ArrayList instead of a fixed size list.

String[] strArray = {"Sun", "Mon", "Tue"};        

//fix sized unmodifiable list

List list = Arrays.asList(strArray);

//create new ArrayList from fixed size list object

list = new ArrayList(list);

ListIterator listItr = list.listIterator();

4) Trying to use add or addAll methods on views

Some methods of various collection classes return a view that is backed by the original collection and does not support add or addAll operations.

One such example is the keySet method of the HashMap class. It returns a Set view of all the keys of the map that does not support add and addAll operations. If you try to call any of these methods on such a view, the code throws UnsupportedOperationException exception as given below.

HashMap<Integer, String> hMapNumbers = new HashMap<Integer, String>();

hMapNumbers.put(1, "One");

hMapNumbers.put(2, "Two");

hMapNumbers.put(3, "Three");

Set<Integer> keys = hMapNumbers.keySet();

Output

Exception in thread "main" java.lang.UnsupportedOperationException

    at java.util.AbstractCollection.add(Unknown Source)

Fix/Resolution

Add element/mappings to the original collection object instead of the view. Since it is just a view, the changes will be reflected in the view if you change the original collection object.

Please let me know your views in the comments section below.