操作 ArrayList 时出现 AbstractList.remove() 中的 UnsupportedOperationException
ArrayList 的列表迭代器确实实现了删除方法,但是,我抛出以下异常:
UnsupportedOperationException at java.util.AbstractList.remove(AbstractList.java:144)
通过此代码:
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();
}
}
}
我在这里缺少什么?我已经验证我传入的 List
确实是 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您可能正在使用
Arrays
实用程序来获取传递给该方法的List
。该对象确实是ArrayList
类型,但它是java.util.Arrays.ArrayList
,而不是java.util.ArrayList
。java.util.Arrays.ArrayList
版本是不可变的,并且其remove()
方法不会被重写。因此,它遵循remove()
的AbstractList
实现,该实现会抛出UnsupportedOperationException
。I think you may be using the
Arrays
utility to get theList
that you pass into that method. The object is indeed of typeArrayList
, but it'sjava.util.Arrays.ArrayList
, notjava.util.ArrayList
.The
java.util.Arrays.ArrayList
version is immutable and itsremove()
method is not overridden. As such, it defers to theAbstractList
implementation ofremove()
, which throws anUnsupportedOperationException
.我怀疑您正在传递 ArrayList,因为 ArrayList 迭代器上的删除方法不会引发该异常。
我猜你正在传递一个 ArrayList 的用户派生类,该类的迭代器在删除时会抛出该异常。
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.