Tuesday, November 26, 2013

Published 11/26/2013 by with 0 comment

java.lang.UnsupportedOperationException at java.util.AbstractList.remove

When you create a java.util.List object from an array using Arrays.asList method and after that if you try to clear or remove the elements from the list you'll get this run time error. The reason is that Arrays.asList method returns a fixed-size list backed by the specified array.

See in the example code below:

int[] myArray = {5,10,15,20};

List intList = Arrays.asList(myArray);

intList.clear();

Or

int[] myArray = {5,10,15,20};

List intList = Arrays.asList(myArray);

for(int i=0;i
{
intList.remove(i);
}

You'll get error from intList.clear() or intList.remove(i) because you cannot remove from a fixed-size array. And also you cannot add any new element in this list.

If you require to copy array elements in a list object and later need to add/delete elements from the list, you can do it in the following way.

  int[] myArray = {5,10,15,20};
List intList = new ArrayList();
System.out.println(intList); // print empty list
//copy the array elements into the list
for(int i=0;i
{
intList.add(myArray[i]);
}
System.out.println(intList); // print list after copying array elements
//You can now add
intList.add(25);
System.out.println(intList); // print list after adding new element
//You can remove
intList.remove(0);
System.out.println(intList); // print list after removing an element
//You can remove all the elements
intList.clear();
System.out.println(intList); // print list after removing all the elements

Below is the output of this sample code:

[]
[5, 10, 15, 20]
[5, 10, 15, 20, 25]
[10, 15, 20, 25]
[]

    email this       edit

0 comments:

Post a Comment