UnsupportedOperationException when using iterator.remove()

前端 未结 3 1497
情深已故
情深已故 2020-12-25 14:20

I\'m trying to remove some elements from a List, but even the simplest examples, as the ones in this answer or this, won\'t work.

public static          


        
相关标签:
3条回答
  • 2020-12-25 14:24

    Arrays.asList() returns a list, backed by the original array. Changes you make to the list are also reflected in the array you pass in. Because you cannot add or remove elements to arrays, that is also impossible to do to lists, created this way, and that is why your remove call fails. You need a different implementation of List (ArrayList, LinkedList, etc.) if you want to be able to add and remove elements to it dynamically.

    0 讨论(0)
  • 2020-12-25 14:30

    Create a new list with the elements you want to remove, and then call removeAll methode.

    List<Object> toRemove = new ArrayList<Object>();
    for(Object a: list){
        if(true){
            toRemove.add(a);
        }
    }
    list.removeAll(toRemove);
    
    0 讨论(0)
  • 2020-12-25 14:47

    This is just a feature of the Arrays.asList() and has been asked before see this question

    You can just wrap this in a new list

    List list = new ArrayList(Arrays.asList("1",...));
    
    0 讨论(0)
提交回复
热议问题