July 12, 2013

java.lang.UnsupportedOperationException



As the name implies when the requested operation is not supported, we get this error.
Below is a sample program to generate this error.

public static void main(String args[])
{
String st[]={"Hi","Hello","Bye"};
List list=Arrays.asList(st);
list.add(“Anand”); //Get error at this line
System.out.println(" List: "+list);
}

 If we run this method, we get the below error because we are trying to add a new element to a list which is not updatable.

Caused by: java.lang.UnsupportedOperationException
                at java.util. List.add(List.java:131)
                at java.util. List.add(List.java:91)
                at Test.main(Test.java:7)

 I modified the program as below to run without errors.

public static void main(String args[])
{
String st[]={"Hi","Hello","Bye"};
ArrayList<String> list = new ArrayList<String>();
//List list=Arrays.asList(st);
list.addAll(Arrays.asList(st));
list.add(“Anand”); //Get error at this line
System.out.println(" List: "+list);
}