Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.UnsupportedOperationException at java.util.AbstractList.remove(Unknown Source)

I have tried below code

String s[]={"1","2","3","4"};   Collection c=Arrays.asList(s);   System.out.println(c.remove("1") +"  remove flag");    System.out.println(" collcetion "+c);   

I was getting

Exception in thread "main" java.lang.UnsupportedOperationException   at java.util.AbstractList.remove(Unknown Source)   at java.util.AbstractList$Itr.remove(Unknown Source)   at java.util.AbstractCollection.remove(Unknown Source)   at test.main(test.java:26)   

Can anyone help me to solve this issue?

like image 924
Deepankar Sarkar Avatar asked Sep 13 '11 09:09

Deepankar Sarkar


People also ask

How do I resolve UnsupportedOperationException in Java?

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.

How do you copy an array to an ArrayList?

We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.


2 Answers

Easy work around is just to pass in the List into an ArrayList's constructor.

For example:

 String valuesInArray[]={"1","2","3","4"};   List modifiableList = new ArrayList(Arrays.asList(valuesInArray)); System.out.println(modifiableList.remove("1") + "  remove flag");   System.out.println(" collcetion "+ modifiableList);  

Response:

true remove flag

collcetion [2, 3, 4]

like image 73
Bojan Petkovic Avatar answered Oct 09 '22 21:10

Bojan Petkovic


Slight correction: no, it's not an unmodifiable Collection. It just doesn't support adding and removing elements, because it is backed by the supplied array and arrays aren't resizeable. But it supports operations like list.set(index, element)

like image 21
Sean Patrick Floyd Avatar answered Oct 09 '22 22:10

Sean Patrick Floyd