Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsupportedOperationException when using iterator.remove()

Tags:

java

iterator

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.

like image 496
user3748908 Avatar asked Jan 23 '15 14:01

user3748908


People also ask

What does remove in an iterator do?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.

How do I fix Java Lang UnsupportedOperationException?

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList , which can be modified. An unmodifiable collection or data structure should not be attempted to be modified.

Why does iterator remove Do not throw ConcurrentModificationException?

Notice that iterator. remove() doesn't throw an exception by itself because it is able to update both the internal state of itself and the collection. Calling remove() on two iterators of the same instance collection would throw, however, because it would leave one of the iterators in an inconsistent state.

Is iterator remove thread safe?

No iterator is thread-safe. If the underlying collection is changed amidst iteration, a ConcurrentModificationException is thrown. Even iterators of synchronized collections are not thread-safe - you have to synchronize manually.


2 Answers

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.

like image 62
Dima Avatar answered Oct 11 '22 01:10

Dima


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",...));
like image 30
joey.enfield Avatar answered Oct 11 '22 00:10

joey.enfield