Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsupportedOperationException in AbstractList.remove() when operating on ArrayList

ArrayList's list iterator does implement the remove method, however, I get the following exception thrown:

UnsupportedOperationException at java.util.AbstractList.remove(AbstractList.java:144) 

By this code:

protected void removeZeroLengthStringsFrom(List<String> stringList) {     ListIterator<String> iter = stringList.listIterator();     String s;     while (iter.hasNext())     {         s = iter.next();         if (s.length() == 0)         {             iter.remove();         }     } } 

What am I missing here? I have verified that the List<String> I am passing in are indeed ArrayList<String>.

Thanks!

like image 715
bguiz Avatar asked Jun 07 '11 02:06

bguiz


People also ask

How do I get rid of 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.

What is UnsupportedOperationException in Java?

public class UnsupportedOperationException extends RuntimeException. Thrown to indicate that the requested operation is not supported. This class is a member of the Java Collections Framework.

What is the use of AbstractList class in Java?

Class AbstractList<E> This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array).

Is AbstractList abstract in Java?

Example 1: AbstractList is an abstract class, so it should be assigned an instance of its subclasses such as ArrayList, LinkedList, or Vector.


2 Answers

I think you may be using the Arrays utility to get the List that you pass into that method. The object is indeed of type ArrayList, but it's java.util.Arrays.ArrayList, not java.util.ArrayList.

The java.util.Arrays.ArrayList version is immutable and its remove() method is not overridden. As such, it defers to the AbstractList implementation of remove(), which throws an UnsupportedOperationException.

like image 68
Mike M Avatar answered Sep 29 '22 18:09

Mike M


I doubt you are being passed an ArrayList, as the remove method on the ArrayList iterator does not throw that exception.

I'm guessing your are being passed a user derived class of ArrayList who's iterator does throw that exception on remove.

public void remove() {     if (lastRet == -1)     throw new IllegalStateException();         checkForComodification();      try {     AbstractList.this.remove(lastRet);     if (lastRet < cursor)         cursor--;     lastRet = -1;     expectedModCount = modCount;     } catch (IndexOutOfBoundsException e) {     throw new ConcurrentModificationException();     } } 
like image 30
MeBigFatGuy Avatar answered Sep 29 '22 16:09

MeBigFatGuy