简体   繁体   中英

UnsupportedOperationException when using iterator.remove()

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 void main(String[] args)
{
    List<String> list = Arrays.asList("1", "2", "3", "4");
    for (Iterator<String> iter = list.listIterator(); iter.hasNext();)
    {
        String a = iter.next();
        if (true)
        {
            iter.remove();
        }
    }
}

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(Unknown Source)
    at java.util.AbstractList$Itr.remove(Unknown Source)

Using a normal Iterator instead of a ListIterator doesn't help. What am I missing? I'm using java 7.

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",...));

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM