Меню

Java lang unsupportedoperationexception ошибка

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[] = {"a", "b", "c"};
        List<String> 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[] = {"a", "b", "c"};
        List<String> list = Arrays.asList(array);

        List<String> 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:

[a, b, c, d]

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!

Привет, сегодня я хотел бы поговорить о культуре проектирования. Многие программисты (особенно джуниоры) боятся создать лишний класс, интерфейс и т.п… Причин тому, я уверен, немало, однако эта тема выходит за рамки этого поста. Но как раз из-за этого появляются очень интересные проблемы, о которых я хотел бы сегодня рассказать. Если я тебя заинтриговал — добро пожаловать под кат.

Как пример возьмем JDK интерфейс Iterator.

public interface Iterator<E> {
    
    boolean hasNext();

    E next();

    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }

} 

Этот код взят именно из JDK 1.8 не просто так. Дело в том, что в JavaDoc’е к методу remove сказано, что он может кидать UnsupportedOperationException, в случае, если реализация интерфейса его не поддерживает. И на мой взгляд это большая проблема. Конечно, я понимаю, что в JDK она вызвана поддержкой обратной совместимости и уже ничего с этим не сделаешь, ничего не сломав.

Я долго думал, как проиллюстрировать эту проблему. И вот, я обратил свое внимание на нее, когда я приехал в гости к другу. Пока друг удалился в кухню за

пивом

соком, я решил включить кондиционер, он был такой же, как и у меня дома и я без вопросов взял пульт и начал клацать. Не работает. Переподключил конциционер к сети, проверил батарейки в пульте, подошел вплотную — и нечего, мой любимый турбо-режим не работает и все, о чем я и пожаловался другу, когда он вернулся. Но тут-то меня и ждал сюрприз: «А в этой модели нет никаких турбо-режимов», — хладнокровно ответил мне друг. «Как так, вот же кнопка „turbo“», — показываю я другу пульт.

Приблизительно такие же чувства я испытываю когда мне прилетает вот такой вот UnsupportedOperationException. На мой взгляд, эта проблема должна решаться простой иерархией интерфейсов, и если с пультами проблема вызвана нерентабельностью, но ведь у нас таких проблем нет 😉

Спасибо за внимание.
Буду рад коментариям и объективной критике.

Содержание

  1. How to Fix the Unsupported Operation Exception in Java
  2. What Causes UnsupportedOperationException
  3. UnsupportedOperationException Example
  4. How to Resolve UnsupportedOperationException
  5. Track, Analyze and Manage Errors With Rollbar
  6. Unsupported Operation Exception Class
  7. Definition
  8. Remarks
  9. Constructors
  10. Fields
  11. Properties
  12. Methods
  13. Explicit Interface Implementations
  14. Extension Methods
  15. Unsupported Operation Exception Class
  16. Definition
  17. Remarks
  18. Constructors
  19. Fields
  20. Properties
  21. Methods
  22. Explicit Interface Implementations
  23. Extension Methods
  24. Все зло UnsupportedOperationException в примерах

How to Fix the Unsupported Operation Exception in Java

Table of Contents

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 :

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:

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:

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

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!

Источник

Unsupported Operation Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Thrown to indicate that the requested operation is not supported.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs an UnsupportedOperationException with no detail message.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs an UnsupportedOperationException with the specified detail message.

Constructs a new exception with the specified detail message and cause.

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ).

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

(Inherited from Throwable) Class (Inherited from Throwable) Handle

The handle to the underlying Android instance.

(Inherited from Throwable) JniIdentityHashCode (Inherited from Throwable) JniPeerMembers LocalizedMessage

Creates a localized description of this throwable.

(Inherited from Throwable) Message

Returns the detail message string of this throwable.

(Inherited from Throwable) PeerReference (Inherited from Throwable) StackTrace (Inherited from Throwable) ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable) Dispose() (Inherited from Throwable) Dispose(Boolean) (Inherited from Throwable) FillInStackTrace()

Fills in the execution stack trace.

(Inherited from Throwable) GetStackTrace()

Provides programmatic access to the stack trace information printed by #printStackTrace() .

(Inherited from Throwable) GetSuppressed()

Returns an array containing all of the exceptions that were suppressed, typically by the try -with-resources statement, in order to deliver this exception.

(Inherited from Throwable) InitCause(Throwable)

Initializes the cause of this throwable to the specified value.

(Inherited from Throwable) PrintStackTrace()

Prints this throwable and its backtrace to the standard error stream.

(Inherited from Throwable) PrintStackTrace(PrintStream)

Prints this throwable and its backtrace to the specified print stream.

(Inherited from Throwable) PrintStackTrace(PrintWriter)

Prints this throwable and its backtrace to the specified print writer.

(Inherited from Throwable) SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Throwable) SetStackTrace(StackTraceElement[])

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable) ToString() (Inherited from Throwable) UnregisterFromRuntime() (Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Throwable)
IJavaPeerable.Finalized() (Inherited from Throwable)
IJavaPeerable.JniManagedPeerState (Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

Unsupported Operation Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Thrown to indicate that the requested operation is not supported.

Portions of this page are modifications based on work created andВ shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs an UnsupportedOperationException with no detail message.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs an UnsupportedOperationException with the specified detail message.

Constructs a new exception with the specified detail message and cause.

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ).

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

(Inherited from Throwable) Class (Inherited from Throwable) Handle

The handle to the underlying Android instance.

(Inherited from Throwable) JniIdentityHashCode (Inherited from Throwable) JniPeerMembers LocalizedMessage

Creates a localized description of this throwable.

(Inherited from Throwable) Message

Returns the detail message string of this throwable.

(Inherited from Throwable) PeerReference (Inherited from Throwable) StackTrace (Inherited from Throwable) ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable) Dispose() (Inherited from Throwable) Dispose(Boolean) (Inherited from Throwable) FillInStackTrace()

Fills in the execution stack trace.

(Inherited from Throwable) GetStackTrace()

Provides programmatic access to the stack trace information printed by #printStackTrace() .

(Inherited from Throwable) GetSuppressed()

Returns an array containing all of the exceptions that were suppressed, typically by the try -with-resources statement, in order to deliver this exception.

(Inherited from Throwable) InitCause(Throwable)

Initializes the cause of this throwable to the specified value.

(Inherited from Throwable) PrintStackTrace()

Prints this throwable and its backtrace to the standard error stream.

(Inherited from Throwable) PrintStackTrace(PrintStream)

Prints this throwable and its backtrace to the specified print stream.

(Inherited from Throwable) PrintStackTrace(PrintWriter)

Prints this throwable and its backtrace to the specified print writer.

(Inherited from Throwable) SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Throwable) SetStackTrace(StackTraceElement[])

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable) ToString() (Inherited from Throwable) UnregisterFromRuntime() (Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Throwable)
IJavaPeerable.Finalized() (Inherited from Throwable)
IJavaPeerable.JniManagedPeerState (Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

Все зло UnsupportedOperationException в примерах

Привет, сегодня я хотел бы поговорить о культуре проектирования. Многие программисты (особенно джуниоры) боятся создать лишний класс, интерфейс и т.п… Причин тому, я уверен, немало, однако эта тема выходит за рамки этого поста. Но как раз из-за этого появляются очень интересные проблемы, о которых я хотел бы сегодня рассказать. Если я тебя заинтриговал — добро пожаловать под кат.

Как пример возьмем JDK интерфейс Iterator.

Этот код взят именно из JDK 1.8 не просто так. Дело в том, что в JavaDoc’е к методу remove сказано, что он может кидать UnsupportedOperationException, в случае, если реализация интерфейса его не поддерживает. И на мой взгляд это большая проблема. Конечно, я понимаю, что в JDK она вызвана поддержкой обратной совместимости и уже ничего с этим не сделаешь, ничего не сломав.

Я долго думал, как проиллюстрировать эту проблему. И вот, я обратил свое внимание на нее, когда я приехал в гости к другу. Пока друг удалился в кухню за пивом соком, я решил включить кондиционер, он был такой же, как и у меня дома и я без вопросов взял пульт и начал клацать. Не работает. Переподключил конциционер к сети, проверил батарейки в пульте, подошел вплотную — и нечего, мой любимый турбо-режим не работает и все, о чем я и пожаловался другу, когда он вернулся. Но тут-то меня и ждал сюрприз: «А в этой модели нет никаких турбо-режимов», — хладнокровно ответил мне друг. «Как так, вот же кнопка „turbo“», — показываю я другу пульт.

Приблизительно такие же чувства я испытываю когда мне прилетает вот такой вот UnsupportedOperationException. На мой взгляд, эта проблема должна решаться простой иерархией интерфейсов, и если с пультами проблема вызвана нерентабельностью, но ведь у нас таких проблем нет 😉

Спасибо за внимание.
Буду рад коментариям и объективной критике.

Источник


public

class
UnsupportedOperationException

extends RuntimeException

java.lang.Object
   ↳ java.lang.Throwable
     ↳ java.lang.Exception
       ↳ java.lang.RuntimeException
         ↳ java.lang.UnsupportedOperationException


Thrown to indicate that the requested operation is not supported.

This class is a member of the

Java Collections Framework.

Summary

Public constructors


UnsupportedOperationException()

Constructs an UnsupportedOperationException with no detail message.


UnsupportedOperationException(String message)

Constructs an UnsupportedOperationException with the specified
detail message.


UnsupportedOperationException(String message, Throwable cause)

Constructs a new exception with the specified detail message and
cause.


UnsupportedOperationException(Throwable cause)

Constructs a new exception with the specified cause and a detail
message of (cause==null ? null : cause.toString()) (which
typically contains the class and detail message of cause).

Inherited methods

From class

java.lang.Throwable


final

void


addSuppressed(Throwable exception)

Appends the specified exception to the exceptions that were
suppressed in order to deliver this exception.

Throwable


fillInStackTrace()

Fills in the execution stack trace.

Throwable


getCause()

Returns the cause of this throwable or null if the
cause is nonexistent or unknown.

String


getLocalizedMessage()

Creates a localized description of this throwable.

String


getMessage()

Returns the detail message string of this throwable.

StackTraceElement[]


getStackTrace()

Provides programmatic access to the stack trace information printed by
printStackTrace().

final

Throwable[]


getSuppressed()

Returns an array containing all of the exceptions that were
suppressed, typically by the try-with-resources
statement, in order to deliver this exception.

Throwable


initCause(Throwable cause)

Initializes the cause of this throwable to the specified value.

void


printStackTrace()

Prints this throwable and its backtrace to the
standard error stream.

void


printStackTrace(PrintWriter s)

Prints this throwable and its backtrace to the specified
print writer.

void


printStackTrace(PrintStream s)

Prints this throwable and its backtrace to the specified print stream.

void


setStackTrace(StackTraceElement[] stackTrace)

Sets the stack trace elements that will be returned by
getStackTrace() and printed by printStackTrace()
and related methods.

String


toString()

Returns a short description of this throwable.

From class

java.lang.Object


Object


clone()

Creates and returns a copy of this object.

boolean


equals(Object obj)

Indicates whether some other object is «equal to» this one.

void


finalize()

Called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.

final

Class<?>


getClass()

Returns the runtime class of this Object.

int


hashCode()

Returns a hash code value for the object.

final

void


notify()

Wakes up a single thread that is waiting on this object’s
monitor.

final

void


notifyAll()

Wakes up all threads that are waiting on this object’s monitor.

String


toString()

Returns a string representation of the object.

final

void


wait(long timeout, int nanos)

Causes the current thread to wait until another thread invokes the
notify() method or the
notifyAll() method for this object, or
some other thread interrupts the current thread, or a certain
amount of real time has elapsed.

final

void


wait(long timeout)

Causes the current thread to wait until either another thread invokes the
notify() method or the
notifyAll() method for this object, or a
specified amount of time has elapsed.

final

void


wait()

Causes the current thread to wait until another thread invokes the
notify() method or the
notifyAll() method for this object.

Public constructors

UnsupportedOperationException

public UnsupportedOperationException ()

Constructs an UnsupportedOperationException with no detail message.

UnsupportedOperationException

public UnsupportedOperationException (String message)

Constructs an UnsupportedOperationException with the specified
detail message.

Parameters
message String: the detail message

UnsupportedOperationException

public UnsupportedOperationException (String message, 
                Throwable cause)

Constructs a new exception with the specified detail message and
cause.

Note that the detail message associated with cause is
not automatically incorporated in this exception’s detail
message.

Parameters
message String: the detail message (which is saved for later retrieval
by the Throwable#getMessage() method).
cause Throwable: the cause (which is saved for later retrieval by the
Throwable#getCause() method). (A null value
is permitted, and indicates that the cause is nonexistent or
unknown.)

UnsupportedOperationException

public UnsupportedOperationException (Throwable cause)

Constructs a new exception with the specified cause and a detail
message of (cause==null ? null : cause.toString()) (which
typically contains the class and detail message of cause).
This constructor is useful for exceptions that are little more than
wrappers for other throwables (for example, PrivilegedActionException).

Parameters
cause Throwable: the cause (which is saved for later retrieval by the
Throwable#getCause() method). (A null value is
permitted, and indicates that the cause is nonexistent or
unknown.)

What is hierarchy of java.lang. UnsupportedOperationException?

-java.lang.Object

-java.lang.Throwable

   -java.lang.UnsupportedOperationException

UnsupportedOperationException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java ?

java.lang.UnsupportedOperationException is a RuntimeExceptions in java.

What is UnsupportedOperationException in java?

UnsupportedOperationException is thrown when requested operation is not supported. Example — Modifying unmodifiable list either by adding or removing elements throws UnsupportedOperationException in java.

  1. java.util.Arrays.asList method returns fixed size list, i.e. unmodifiable list and Modifying unmodifiable list either by adding or removing elements throws UnsupportedOperationException in java

  2. making list unmodifiable using Collections.unmodifiableList and Modifying unmodifiable list either by adding or removing elements throws java.lang.UnsupportedOperationException in java.

  3. making set unmodifiable using Collections.unmodifiableSet and Modifying unmodifiable set either by adding or removing elements throws java.lang.UnsupportedOperationException in java

  4. making map unmodifiable using Collections.unmodifiableMap and Modifying unmodifiable map either by adding or removing key-value pair throws java.lang.UnsupportedOperationException in java

Scenarios where UnsupportedOperationException may be thrown in java>

Program/Example 1 > java.util.Arrays.asList method returns fixed size list, i.e. unmodifiable list and Modifying unmodifiable list either by adding or removing elements throws UnsupportedOperationException in java

package unsupportedOperationExceptionExamplePackage;

import java.util.Arrays;

import java.util.List;

public class UnsupportedOperationExceptionExample {

public static void main(String[] args) {

     String stringArray[] = {«a», «b»};

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

     System.out.println(list);

     list.add(«c»); //It will throw java.lang.UnsupportedOperationException

}

}

/*OUTPUT

[a, b]

Exception in thread «main» java.lang.UnsupportedOperationException

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

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

at unsupportedOperationExceptionExamplePackage.UnsupportedOperationExceptionExample.main(UnsupportedOperationExceptionExample.java:11)

*/

Program/Example 2 >ArrayList — making list unmodifiable using Collections.unmodifiableList and Modifying unmodifiable list either by adding or removing elements throws java.lang.UnsupportedOperationException in java

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

/**

* Copyright (c), AnkitMittal JavaMadeSoEasy.com

*/

public class ArrayListTest {

   public static void main(String args[]) {

          // creates array with initial capacity of 10.

          List<String> arrayList = new ArrayList<String>();

          arrayList.add(«ankit»);

          arrayList.add(«javaMadeSoEasy»);

          // getting unmodifiable list

          List<String> unmodifiableList = Collections.unmodifiableList(arrayList);

          /*

          * Now any attempt to modify list will throw java.lang.UnsupportedOperationException

          */

          unmodifiableList.add(«mittal»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)

   at ArrayListTest.main(ArrayListTest.java:24)

*/

Program/Example 3 >LinkedList — making list unmodifiable using Collections.unmodifiableList and Modifying unmodifiable list either by adding or removing elements throws java.lang.UnsupportedOperationException in java

import java.util.LinkedList;

import java.util.Collections;

import java.util.List;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class LinkedListUnModifiableExample {

   public static void main(String args[]) {

          List<String> linkedList = new LinkedList<String>();

          linkedList.add(«ankit»);

          linkedList.add(«javaMadeSoEasy»);

          // getting unmodifiable list

          List<String> unmodifiableList = Collections.unmodifiableList(linkedList);

          /*

          * Now any attempt to modify list will throw java.lang.UnsupportedOperationException

          */

          unmodifiableList.add(«mittal»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)

   at LinkedListUnModifiableExample .main(LinkedListTest.java:23)

*/

Program/Example 4 >HashSet — making set unmodifiable using Collections.unmodifiableSet and Modifying unmodifiable set either by adding or removing elements throws java.lang.UnsupportedOperationException in java

import java.util.Collections;

import java.util.HashSet;

import java.util.Set;

/**

* Copyright (c), AnkitMittal JavaMadeSoEasy.com

*/

public class HashSetTest {

   public static void main(String args[]) {

          // creates array with initial capacity of 10.

          Set<String> hashSet = new HashSet<String>();

          hashSet.add(«ankit»);

          hashSet.add(«javaMadeSoEasy»);

          // getting unmodifiable HashSet

          Set<String> unmodifiableSet = Collections.unmodifiableSet(hashSet);

          /*

          * Now any attempt to modify list will throw java.lang.UnsupportedOperationException

          */

          unmodifiableSet.add(«mittal»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)

   at HashSetTest.main(HashSetTest.java:24)

*/

Program/Example 5 >HashMap — making map unmodifiable using Collections.unmodifiableMap and Modifying unmodifiable map either by adding or removing key-value pair throws java.lang.UnsupportedOperationException in java

import java.util.Collections;

import java.util.HashMap;

import java.util.Map;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class HashMapTest {

   public static void main(String args[]){

          Map<Integer,String> hashMap=new HashMap<Integer,String>();

          hashMap.put(11, «ankit»);

          hashMap.put(21, «mittal»);

          hashMap.put(31, «javaMadeSoEasy»);

          //getting unmodifiable HashMap

          Map<Integer,String> unmodifiableMap = Collections.unmodifiableMap(hashMap);

          /*

          * Now any attempt to modify map will throw java.lang.UnsupportedOperationException

          */

          unmodifiableMap.put(41,«java»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableMap.put(Unknown Source)

   at HashMapTest.main(hashMapTest.java:24)

*/

Program/Example 6 >LinkedHashSet  — making set unmodifiable using Collections.unmodifiableSet and Modifying unmodifiable set either by adding or removing elements throws java.lang.UnsupportedOperationException in java

import java.util.Collections;

import java.util.LinkedHashSet;

import java.util.Set;

/**

* Copyright (c), AnkitMittal JavaMadeSoEasy.com

*/

public class LinkedHashSetUnmodifiableExample {

   public static void main(String args[]) {

          // creates array with initial capacity of 10.

          Set<String> linkedLinkedHashSet = new LinkedHashSet<String>();

          linkedLinkedHashSet.add(«ankit»);

          linkedLinkedHashSet.add(«javaMadeSoEasy»);

          // getting unmodifiable LinkedHashSet

          Set<String> unmodifiableSet = Collections.unmodifiableSet(linkedLinkedHashSet);

          /*

          * Now any attempt to modify list will throw java.lang.UnsupportedOperationException

          */

          unmodifiableSet.add(«mittal»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)

   at main(LinkedHashSetUnmodifiableExample.java:24)

*/

Program/Example 7 > Hashtable — making map unmodifiable using Collections.unmodifiableMap and Modifying unmodifiable map either by adding or removing key-value pair throws java.lang.UnsupportedOperationException in java

Map hierarchy in java — Detailed — HashMap, Hashtable, ConcurrentHashMap, LinkedHashMap, TreeMap, ConcurrentSkipListMap, IdentityHashMap, WeakHashMap, EnumMap classes

import java.util.Collections;

import java.util.Hashtable;

import java.util.Map;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class HashtableTest {

   public static void main(String args[]){

          Map<Integer,String> hashtable=new Hashtable<Integer,String>();

          hashtable.put(11, «ankit»);

          hashtable.put(21, «mittal»);

          hashtable.put(31, «javaMadeSoEasy»);

          //getting unmodifiable Hashtable

          Map<Integer,String> unmodifiableMap = Collections.unmodifiableMap(hashtable);

          /*

          * Now any attempt to modify map will throw java.lang.UnsupportedOperationException

          */

          unmodifiableMap.put(41,«java»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableMap.put(Unknown Source)

   at hashtableTest.main(hashtableTest.java:24)

*/

Program/Example 8 >

ConcurrentSkipListMap — making map unmodifiable using Collections.unmodifiableMap in java and Modifying unmodifiable map either by adding or removing key-value pair throws java.lang.UnsupportedOperationException in java

HashMap vs Hashtable vs LinkedHashMap vs TreeMap — Differences

import java.util.Collections;

import java.util.Map;

import java.util.concurrent.ConcurrentSkipListMap;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class ConcurrentSkipListMapUnmodifiableExample {

   public static void main(String args[]){

          Map<Integer,String> concurrentSkipListMap=new ConcurrentSkipListMap<Integer,String>();

          concurrentSkipListMap.put(11, «ankit»);

          concurrentSkipListMap.put(21, «mittal»);

          concurrentSkipListMap.put(31, «javaMadeSoEasy»);

          //getting unmodifiable ConcurrentSkipListMap

          Map<Integer,String> unmodifiableMap = Collections.unmodifiableMap(concurrentSkipListMap);

          /*

          * Now any attempt to modify map will throw java.lang.UnsupportedOperationException

          */

          unmodifiableMap.put(41,«java»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableMap.put(Unknown Source)

   at concurrentSkipListMapTest.main(concurrentSkipListMapTest.java:24)

*/

Program/Example 9 >

TreeMap — making map unmodifiable using Collections.unmodifiableMap and Modifying unmodifiable map either by adding or removing key-value pair throws java.lang.UnsupportedOperationException in java

HashMap vs Hashtable vs LinkedHashMap vs TreeMap — Differences

import java.util.Collections;

import java.util.TreeMap;

import java.util.Map;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class TreeMapUnmodifiableExample {

   public static void main(String args[]){

          Map<Integer,String> treeMap=new TreeMap<Integer,String>();

          treeMap.put(11, «ankit»);

          treeMap.put(21, «mittal»);

          treeMap.put(31, «javaMadeSoEasy»);

          //getting unmodifiable TreeMap

          Map<Integer,String> unmodifiableMap = Collections.unmodifiableMap(treeMap);

          /*

          * Now any attempt to modify map will throw java.lang.UnsupportedOperationException

          */

          unmodifiableMap.put(41,«java»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableMap.put(Unknown Source)

   at treeMapTest.main(treeMapTest.java:24)

*/

Program/Example 10 >

ConcurrentHashMap — making map unmodifiable using Collections.unmodifiableMap and Modifying unmodifiable map either by adding or removing key-value pair throws java.lang.UnsupportedOperationException in java

HashMap and ConcurrentHashMap — Similarity and Differences

HashMap vs Hashtable vs LinkedHashMap vs TreeMap — Differences

import java.util.Collections;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class ConcurrentHashMapUnmodifiableExample {

   public static void main(String args[]){

          Map<Integer,String> concurrentHashMap=new ConcurrentHashMap<Integer,String>();

          concurrentHashMap.put(11, «ankit»);

          concurrentHashMap.put(21, «mittal»);

          concurrentHashMap.put(31, «javaMadeSoEasy»);

          //getting unmodifiable ConcurrentHashMap

          Map<Integer,String> unmodifiableMap = Collections.unmodifiableMap(concurrentHashMap);

          /*

          * Now any attempt to modify map will throw java.lang.UnsupportedOperationException

          */

          unmodifiableMap.put(41,«java»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableMap.put(Unknown Source)

   at  ConcurrentHashMapUnmodifiableExample.main(ConcurrentHashMapUnmodifiableExample.java:24)

*/

Program/Example 11 >LinkedHashMap — making map unmodifiable using Collections.unmodifiableMap and Modifying unmodifiable map either by adding or removing key-value pair throws java.lang.UnsupportedOperationException in java

HashMap vs Hashtable vs LinkedHashMap vs TreeMap — Differences

Map hierarchy in java — Detailed — HashMap, Hashtable, ConcurrentHashMap, LinkedHashMap, TreeMap, ConcurrentSkipListMap, IdentityHashMap, WeakHashMap, EnumMap classes

import java.util.Collections;

import java.util.LinkedHashMap;

import java.util.Map;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class LinkedHashMapTest {

   public static void main(String args[]){

          Map<Integer,String> linkedHashMap=new LinkedHashMap<Integer,String>();

          linkedHashMap.put(11, «ankit»);

          linkedHashMap.put(21, «mittal»);

          linkedHashMap.put(31, «javaMadeSoEasy»);

          //getting unmodifiable LinkedHashMap

          Map<Integer,String> unmodifiableMap = Collections.unmodifiableMap(linkedHashMap);

          /*

          * Now any attempt to modify map will throw java.lang.UnsupportedOperationException

          */

          unmodifiableMap.put(41,«java»);

   }

}

/*OUTPUT

Exception in thread «main» java.lang.UnsupportedOperationException

   at java.util.Collections$UnmodifiableMap.put(Unknown Source)

   at linkedHashMapTest.main(linkedHashMapTest.java:24)

*/

How to Avoid or Solve UnsupportedOperationException in java >

Never try to modify list, set or map which has been made unmodifiable.

  • Never modify list returned by  java.util.Arrays.asList method to avoid java.lang.UnsupportedOperationException in java

  • Never modify list which has been made unmodifiable using Collections.unmodifiableList method to avoid java.lang.UnsupportedOperationException in java

  • Never modify set which has been made unmodifiable using Collections.unmodifiableSet method to avoid java.lang.UnsupportedOperationException in java.

  • Never modify map which has been made unmodifiable using Collections.unmodifiableMap method to avoid java.lang.UnsupportedOperationException in java.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    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

    Java

    import java.util.Arrays;

    import java.util.List;

    public class Example {

        public static void main(String[] args)

        {

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

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

            System.out.println(l);

            l.add("Mango");

        }

    }

    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. 

    Java

    import java.util.ArrayList;

    import java.util.List;

    import java.util.*;

    public class Example {

        public static void main(String[] args) {

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

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

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

            l.add("Mango");

            for(String s: l )

              System.out.println(s);

        }

    }

    Public Constructor Summary

    Inherited Method Summary


    From class
    java.lang.Object

    Object

    clone()

    Creates and returns a copy of this Object.

    boolean

    equals(Object obj)

    Compares this instance with the specified object and indicates if they
    are equal.

    void

    finalize()

    Invoked when the garbage collector has detected that this instance is no longer reachable.

    final

    Class<?>

    getClass()

    Returns the unique instance of Class that represents this
    object’s class.

    int

    hashCode()

    Returns an integer hash code for this object.

    final

    void

    notify()

    Causes a thread which is waiting on this object’s monitor (by means of
    calling one of the wait() methods) to be woken up.

    final

    void

    notifyAll()

    Causes all threads which are waiting on this object’s monitor (by means
    of calling one of the wait() methods) to be woken up.

    String

    toString()

    Returns a string containing a concise, human-readable description of this
    object.

    final

    void

    wait(long timeout, int nanos)

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
    specified timeout expires.

    final

    void

    wait(long timeout)

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
    specified timeout expires.

    final

    void

    wait()

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

    Public Constructors


    public


    UnsupportedOperationException
    ()

    Constructs an UnsupportedOperationException with no detail message.


    public


    UnsupportedOperationException
    (String message)

    Constructs an UnsupportedOperationException with the specified
    detail message.

    Parameters
    message the detail message


    public


    UnsupportedOperationException
    (String message, Throwable cause)

    Constructs a new exception with the specified detail message and
    cause.

    Note that the detail message associated with cause is
    not automatically incorporated in this exception’s detail
    message.

    Parameters
    message the detail message (which is saved for later retrieval
    by the Throwable.getMessage() method).
    cause the cause (which is saved for later retrieval by the
    Throwable.getCause() method). (A null value
    is permitted, and indicates that the cause is nonexistent or
    unknown.)


    public


    UnsupportedOperationException
    (Throwable cause)

    Constructs a new exception with the specified cause and a detail
    message of (cause==null ? null : cause.toString()) (which
    typically contains the class and detail message of cause).
    This constructor is useful for exceptions that are little more than
    wrappers for other throwables (for example, PrivilegedActionException).

    Parameters
    cause the cause (which is saved for later retrieval by the
    Throwable.getCause() method). (A null value is
    permitted, and indicates that the cause is nonexistent or
    unknown.)

    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии

    А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Java lang securityexception ошибка как исправить на андроид
  • Java lang runtimeexception ошибка андроид