Java collection add unsupportedoperationexception

java.lang.UnsupportedOperationException – How to handle UnsupportedOperationException

In this tutorial we will discuss about UnsupportedOperationException in Java. This exception is thrown to indicate that the requested operation is not supported. This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause. Moreover, the UnsupportedOperationException exists since the 1.2 version of Java. Finally, the UnsupportedOperationException is a member of the Java Collections Framework.

The Structure of UnsupportedOperationException

Constructors

Creates an instance of the UnsupportedOperationException class, setting null as its message.

Creates an instance of the UnsupportedOperationException class, using the specified string as message. The string argument indicates the name of the class that threw the error.

Creates an instance of the UnsupportedOperationException class, using the specified parameters as message cause respectively.

The UnsupportedOperationException in Java

The UnsupportedOperationException indicates that the requested operation cannot be performed, due to the fact that it is forbidden for that particular class. The following methods create unmodifiable views of different collections:

These views are read-only and thus, cannot be modified. If an application tries to modify such view, an UnsupportedOperationException is thrown. The following examples indicate the aforementioned cases:

UnsupportedOperationExceptionExample_Collection.java:

import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Random; public class UnsupportedOperationExceptionExampleCollection < private final static int TOTAL_ELEMS = 10; private final static Random random = new Random(); public static void main(String[] args) < Collection integers = new HashSet(TOTAL_ELEMS); // Fill the collection with some random values. for(int i = 0; i < TOTAL_ELEMS; ++i) integers.add(random.nextInt()); // Retrieve an unmodifiable view of the collection. Collection unmodifiableCollection = Collections.unmodifiableCollection(integers); // This statement throws an UnsupportedOperationException. unmodifiableCollection.add(random.nextInt()); >>

In this example, we created an instance of the HashSet class, which implements the Collection interface, and inserted a number of random values. Then, we retrieved an unmodifiable view of the Collection and tried to insert a new element, which resulted to an UnsupportedOperationException .

UnsupportedOperationExceptionExampleSet.java:

import java.util.Collections; import java.util.HashSet; import java.util.Random; import java.util.Set; public class UnsupportedOperationExceptionExampleSet < private final static int TOTAL_ELEMS = 10; private final static Random random = new Random(); public static void main(String[] args) < Set integers = new HashSet(TOTAL_ELEMS); // Fill the set with some random values. for(int i = 0; i < TOTAL_ELEMS; ++i) integers.add(random.nextInt()); // Retrieve an unmodifiable view of the set. Set unmodifiableSet = Collections.unmodifiableSet(integers); // This statement throws an UnsupportedOperationException. unmodifiableSet.add(random.nextInt()); >>

In this example, we created an instance of the HashSet class and inserted a number of random values. Then, we retrieved an unmodifiable view of the HashSet and tried to insert a new element, which resulted to an UnsupportedOperationException .

Читайте также:  METANIT.COM

UnsupportedOperationExceptionExampleSortedSet.java:

import java.util.Collections; import java.util.Random; import java.util.SortedSet; import java.util.TreeSet; public class UnsupportedOperationExceptionExampleSortedSet < private final static int TOTAL_ELEMS = 10; private final static Random random = new Random(); public static void main(String[] args) < TreeSet integers = new TreeSet(); // Fill the tree set with some random values. for(int i = 0; i < TOTAL_ELEMS; ++i) integers.add(random.nextInt()); // Retrieve an unmodifiable view of the tree set. SortedSet unmodifiableSortedSet = Collections.unmodifiableSortedSet(integers); // This statement throws an UnsupportedOperationException. unmodifiableSortedSet.add(random.nextInt()); >>

In this example, we created an instance of the TreeSet class and inserted a number of random values. Then, we retrieved an unmodifiable view of the TreeSet and tried to insert a new element, which resulted to an UnsupportedOperationException .

UnsupportedOperationExceptionExampleList.java:

import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class UnsupportedOperationExceptionExampleList < private final static int TOTAL_ELEMS = 10; private final static Random random = new Random(); public static void main(String[] args) < List integers = new ArrayList(TOTAL_ELEMS); // Fill the list with some random values. for(int i = 0; i < TOTAL_ELEMS; ++i) integers.add(random.nextInt()); // Retrieve an unmodifiable view of the list. List unmodifiableList = Collections.unmodifiableList(integers); // This statement throws an UnsupportedOperationException. unmodifiableList.add(random.nextInt()); >>

In this example, we created an instance of the ArrayList class and inserted a number of random values. Then, we retrieved an unmodifiable view of the ArrayList and tried to insert a new element, which resulted to an UnsupportedOperationException .

UnsupportedOperationExceptionExampleMap.java:

import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Random; public class UnsupportedOperationExceptionExampleMap < private final static int TOTAL_ELEMS = 10; private final static Random random = new Random(); public static void main(String[] args) < Map map = new HashMap(); // Fill the map with some random values. for(int i = 0; i < TOTAL_ELEMS; ++i) map.put(("key_" + i), random.nextInt()); // Retrieve an unmodifiable view of the map. Map unmodifiableMap = Collections.unmodifiableMap(map); // This statement throws an UnsupportedOperationException. unmodifiableMap.put("KEY", random.nextInt()); >>

In this example, we created an instance of the HashMap class and inserted a number of random values. Then, we retrieved an unmodifiable view of the HashMap and tried to insert a new element, which resulted to an UnsupportedOperationException .

UnsupportedOperationExceptionExampleSortedMap.java:

import java.util.Collections; import java.util.Random; import java.util.SortedMap; import java.util.TreeMap; public class UnsupportedOperationExceptionExampleSortedMap < private final static int TOTAL_ELEMS = 10; private final static Random random = new Random(); public static void main(String[] args) < TreeMap map = new TreeMap(); // Fill the tree map with some random values. for(int i = 0; i < TOTAL_ELEMS; ++i) map.put(("key_" + i), random.nextInt()); // Retrieve an unmodifiable view of the tree map. SortedMap unmodifiableSortedMap = Collections.unmodifiableSortedMap(map); // This statement throws an UnsupportedOperationException. unmodifiableSortedMap.put("KEY", random.nextInt()); >>

In this example, we created an instance of the TreeMap class and inserted a number of random values. Then, we retrieved an unmodifiable view of the TreeMap and tried to insert a new element, which resulted to an UnsupportedOperationException .

Читайте также:  Java and memory leak

How to deal with the UnsupportedOperationException

  • This exception is easy to deal with, because it indicates which method cannot be used. Thus, if your application requires the modification of some collection or data structures, you shall avoid using unmodifiable views.
  • Also, if this exception is thrown by a class of an external library, you shall consult its documentation, in order to understand why this particular exception is thrown.

Download the Eclipse Project

This was a tutorial about the UnsupportedOperationException in Java.

Источник

How to Fix the Unsupported Operation Exception in Java

How to Fix the Unsupported Operation Exception in Java

An UnsupportedOperationException is a runtime exception in Java that occurs when a requested operation is not supported. For example, if an unmodifiable List is attempted to be modified by adding or removing elements, an UnsupportedOperationException is thrown. This is one of the common exceptions that occur when working with Java collections such as List, Queue, Set and Map.

The UnsupportedOperationException is a member of the Java Collections Framework. Since it is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.

What Causes UnsupportedOperationException

An UnsupportedOperationException is thrown when a requested operation cannot be performed because it is not supported for that particular class. One of the most common causes for this exception is using the asList() method of the java.util.Arrays class. Since this method returns a fixed-size unmodifiable List , the add() or remove() methods are unsupported. Trying to add or remove elements from such a List will throw the UnsupportedOperationException exception.

Other cases where this exception can occur include:

  • Using wrappers between collections and primitive types.
  • Trying to remove elements using an Iterator .
  • Trying to add, remove or set elements using ListIterator .

UnsupportedOperationException Example

Here’s an example of an UnsupportedOperationException thrown when an object is attempted to be added to an unmodifiable List :

import java.util.Arrays; import java.util.List; public class UnsupportedOperationExceptionExample < public static void main(String[] args) < String array[] = ; List list = Arrays.asList(array); list.add("d"); > >

Since the Arrays.asList() method returns a fixed-size list, attempting to modify it either by adding or removing elements throws an UnsupportedOperationException .

Running the above code throws the exception:

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 UnsupportedOperationExceptionExample.main(UnsupportedOperationExceptionExample.java:8)

How to Resolve UnsupportedOperationException

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList , which can be modified. An unmodifiable collection or data structure should not be attempted to be modified.

The unmodifiable List returned by the Arrays.asList() method in the earlier example can be passed to a new ArrayList object, which can be modified:

import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class UnsupportedOperationExceptionExample < public static void main(String[] args) < String array[] = ; List list = Arrays.asList(array); List arraylist = new ArrayList<>(list); arraylist.add("d"); System.out.println(arraylist); > >

Here, a new ArrayList object is created using the unmodifiable list returned from the Arrays.asList() method. When a new element is added to the ArrayList , it works as expected and resolves the UnsupportedOperationException. Running the above code produces the following output:

Читайте также:  Ссылки

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Источник

Java UnsupportedOperationException

The UnsupportedOperationException class is a member of the Java Collections Framework since Java version 1.2. It extends RuntimeException; hence, it is an unchecked exception and needs not to be declared in a method’s or a constructor’s throws clause.

public class UnsupportedOperationException extends RuntimeException

1. Root Cause of UnsupportedOperationException

As the name implies, UnsupportedOperationException occurs when a requested operation is not supported in a class or interface. It is a common exception that occurs while working with collections such as List, Queue, Set and Map. For example, if we try to modify an unmodifiable Map or List, this exception is thrown.

One of the most common occurrences is while using Arrays.asList() method. Since asList() method returns a fixed-size unmodifiable List, the add() or remove() methods are not supported. If we try to add or remove elements from this list, it will throw UnsupportedOperationException.

List list = Arrays.asList(new String[] < "a", "b", "c" >); list.add("d"); //or list.remove("a");

We will get the UnsupportedOperationException in the console.

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 UnsupportedOperationExceptionExample.main(UnsupportedOperationExceptionExample.java:8) 

2. Resolving UnsupportedOperationException

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList. If we have unmodifiable collections, we can wrap them under a mutable alternative collection class.

For example, the unmodifiable List in the earlier example can be passed to a new ArrayList object, a mutable collection.

List list = Arrays.asList(new String[] < "a", "b", "c" >); List arraylist = new ArrayList<>(list); //Works fine arraylist.add("d"); arraylist.remove("a");

Here, a new ArrayList object is created using the unmodifiable list returned from the Arrays.asList() method. When a new element is added to the ArrayList, it works as expected and resolves the UnsupportedOperationException.

3. Conclusion

In this article, we learned about UnsupportedOperationException, what are the causes for this and how to prevent it in our code.

Источник

Оцените статью