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!
I think you may be using the
Arraysutility to get theListthat you pass into that method. The object is indeed of typeArrayList, but it’sjava.util.Arrays.ArrayList, notjava.util.ArrayList.The
java.util.Arrays.ArrayListversion is immutable and itsremove()method is not overridden. As such, it defers to theAbstractListimplementation ofremove(), which throws anUnsupportedOperationException.