Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing a value from a list<String> in java throws java.lang.UnsupportedOperationException

Tags:

java

list

I want to remove specific elements from my List. I don't want to do this while iterating through the list. I want to specify the value which has to be deleted. In javadocs I found the function List.remove(Object 0) This is my code :

         String str="1,2,3,4,5,6,7,8,9,10";
         String[] stra=str.split(",");
         List<String> a=Arrays.asList(stra);
         a.remove("2");
         a.remove("3");

But I get an Exception : java.lang.UnsupportedOperationException

like image 388
Ashwin Avatar asked May 17 '12 12:05

Ashwin


2 Answers

The problem is that Arrays.asList() returns a list that doesn't support insertion/removal (it's simply a view onto stra).

To fix, change:

List<String> a = Arrays.asList(stra);

to:

List<String> a = new ArrayList<String>(Arrays.asList(stra));

This makes a copy of the list, allowing you to modify it.

like image 180
NPE Avatar answered Oct 22 '22 05:10

NPE


http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29

See this. Arrays.asList returns a fixed list. Which is an immutable one. By its definition you cant modify that object once it creates.Thats why it is throwing unsupported exception.

like image 28
Eshan Sudharaka Avatar answered Oct 22 '22 06:10

Eshan Sudharaka