Tuesday 3 November 2015

What is UnsupportedOperationException?


UnsupportedOperationException:- The UnsupportedOperationException is thrown when you try to call a collections-related method on an instance of a collection's interface that does not provide a complete implementation of that interface.If a collection is a fixed-size or read-only collection, you can''t add or remove elements from it.Trying to perform such an operation causes this exception to be thrown.


Sample Program:-


import java.util.Arrays;  
 import java.util.List;  
 public class UnsupportedOperationExceptionExample {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String[] s = { "a", "b" };  
           List l1 = Arrays.asList(s);  
           l1.add("c");  
      }  
 }  

Output:-


 Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.AbstractList.add(Unknown Source)  
      at java.util.AbstractList.add(Unknown Source)  
      at ConcurrentModificationExceptionExample.main(ConcurrentModificationExceptionExample.java:20) 

In above program, Arrays.asList() returns a fixed-length collection, so you can't add anything without causing the exception to be thrown.


Enjoy Reading.

No comments:

Post a Comment