Removing value from list <String> in java throws java.lang.UnsupportedOperationException
I want to remove certain items from my list. I do not want to do this by repeating the list. I want to specify the value to be deleted. In javadocs, I found the List.remove(Object 0) 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
The problem is that Arrays.asList() returns a list that does not support insert / delete (this is just a view on stra ).
To fix, change:
List<String> a = Arrays.asList(stra); in
List<String> a = new ArrayList<String>(Arrays.asList(stra)); This makes a copy of the list, allowing you to change it.
http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29
Take a look. Arrays.asList returns a fixed list. What is immutable. By its definition, you cannot change this object after it is created. Therefore, it throws an unsupported exception.