Wednesday, 9 October 2019

UnsupportedOperationException When Adding or Removing Elements from a Collection in Java

          In the previous article, we discussed the differences between HashSet and TreeSet and explored practical examples of both. In this article, we will discuss one of the important exceptions in the Java Collections Framework: UnsupportedOperationException.


What is UnsupportedOperationException in collection?

          As the name suggests, UnsupportedOperationException indicates that the requested operation is not supported. It is thrown when you attempt to perform an operation on a collection or object that does not support that operation.

UnsupportedOperationException is thrown at runtime, which means it is a subclass of RuntimeException and therefore an unchecked exception.


Throwable -> Exception -> RuntimeException -> UnsupportedOperationException


Scenarios That Throw UnsupportedOperationException:-

1) Update on list of Arrays.asList() 

      As we know, the asList() method of the Arrays (java.util.Arrays) class is used to convert an array into a List.

However, the list returned by Arrays.asList() is a fixed-size list backed by the original array. If you try to add or remove elements from this list, Java throws an UnsupportedOperationException, as demonstrated in the example below.


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));
       }
}
Output:-
Mechanical
Computer Science
ECE



2) Update on Unmodifiable collection

           You can create an unmodifiable collection by using the Collections.unmodifiableCollection(Collection<? extends E> c) method or one of its related methods, such as Collections.unmodifiableList(), Collections.unmodifiableSet(), or Collections.unmodifiableMap().

An unmodifiable collection provides read-only access to its elements. You can read or iterate over the collection, but you cannot perform structural modifications such as adding, removing, or updating elements through the unmodifiable view. If you attempt to modify an unmodifiable collection, Java throws an UnsupportedOperationException, which is an unchecked exception (RuntimeException).

The following example demonstrates how an UnsupportedOperationException is thrown when attempting to modify an unmodifiable collection.


UnsupportedOpExceptionExample.java
package com.example.demo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class UnsupportedOpExceptionExample {

        public static void main(String[] args) {

               List<String> list = new ArrayList<String>();
               list.add("Mechanical");
               list.add("ECE");
               Collection<String> strList = Collections.unmodifiableCollection(list);
               strList.add("CS");

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

}

Output:-
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source) at com.example.demo.UnsupportedOpExceptionExample.main(UnsupportedOpExceptionExample.java:16)


  Use an unmodifiable collection only when the collection is intended to be read-only and no modifications are required. If you need to add, remove, or update elements, avoid using an unmodifiable collection.

Thank you for visiting the blog!..

No comments:

Post a Comment