UnsupportedOperationException while removing or adding elements from List
- By Viral Patel on November 21, 2008
While running following code, UnsupportedOperationException is thrown both at .add() and .remove() method. What is the problem with the code?
List myNewList = Array.asList(someArrayOfLong); myNewList.add(new Long(15)); //add an element in the list. myNewList.remove(0); //remove element from the list at index 0.
By the time you get to the remove(i) statement, list is no longer a java.util.ArrayList. When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.
Get our Articles via Email. Enter your email address.