UnsupportedOperationException while removing or adding elements from List

Problem statement:
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.



  • supriya 1 April, 2010, 13:57

    i was facing the same problem,”UnsupportedOperationException while removing or adding elements from List.”
    what i did was took the arrays.aslist result in new Arraylist and used addAll method to add in it..then we can perform the add/remove from newly created and populated list.

    //Customer_Orders was converted to list by using Arrays.aslist
    //was giving exception on remove


    //what i did was

    List list1= new ArrayList();
    list1.addAll(Arrays.asList(customer_Orders)) ;

    //perform operation on list1

    • Nasrin 22 December, 2011, 1:18

      Thanks, this surly helped me.

  • Max Nanasy 30 August, 2012, 4:25

    What do you mean by “By the time you get to the remove(i) statement, list is no longer a java.util.ArrayList.”?
    A. It crashes before that line
    B. list was never a java.util.ArrayList

  • Salim 9 September, 2013, 2:02

    More easy solution is to replace :
    List myNewList = Array.asList(someArrayOfLong);
    by :
    List myNewList = new ArrayList(Array.asList(someArrayOfLong));
    I think it resoled the problem

  • sridevi 17 September, 2013, 16:37

    Thank you so muck your post is resolved my problem

  • gayatri 6 August, 2014, 15:27

    i’m getting some exception when doing add operation on Collections.unmodifiableList like unsupported operation.can you pls provide a solution for this?

  • gayatri 6 August, 2014, 15:32

    Collections.unmodifiableList(new ArrayList(map.values()))
    getting unsupportedException
    pls help

Leave a Reply

Your email address will not be published. Required fields are marked *


To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]