3

UnsupportedOperationException when adding or removing element to a Collection in...

 2 years ago
source link: http://adnjavainterview.blogspot.com/2019/10/unsupportedoperationexception-when-adding-or-removing-element-to-collection-in-java.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

UnsupportedOperationException when adding or removing element to a Collection in java

        In earlier article, we discussed the difference between HashSet and TreeSet and also covered sample example of TreeSet and HashSet.  In the current article, we will see one of important exception in collection i.e UnsupportedOperationException.

What is UnsupportedOperationException in collection?

The name itself suggests provided operation can not be  supported i.e when you try to perform some operation on collection where it's not allowed and will throw UnsupportedOperationException. The UnsupportedOperationException is thrown at run time so it's RuntimeException i.e Unchecked Exception.

Throwable -> Exception -> RuntimeException -> UnsupportedOperationException


Scenario to throw UnsupportedOperationException:-

1) Update on list of Arrays.asList() 

As we know that, Converting from Array to List we will use asList() method of Arrays(java.util.Arrays) class.  When you convert array to list using asList method, and try to add an element to a list then will throw UnsupportedOperationException as shown below code.

UnsupportedOpExceptionExample.java,
package com.example.demo;

import java.util.Arrays;
import java.util.List;

public class UnsupportedOpExceptionExample {

        public static void main(String[] args) {

                String[] arrayStr = { "Mechanical", "Computer Science" };
                List<String> list = Arrays.asList(arrayStr);
                list.add("ECE");

         }

}
Output:-
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at com.example.demo.UnsupportedOpExceptionExample.main(UnsupportedOpExceptionExample.java:12)

Solution:-

Pass Arrays.asList to the List constructor, so that will act as new ArrayList object, then you can modify the list without any exception.

UnsupportedOpExceptionExample.java
package com.example.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UnsupportedOpExceptionExample {

       public static void main(String[] args) {

              String[] arrayStr = { "Mechanical", "Computer Science" };
              List<String> list = new ArrayList<String>(Arrays.asList(arrayStr));
              list.add("ECE");

              list.stream().forEach(str -> System.out.println(str));
       }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK