首先给出一段代码:
public class AslistMethod {
public static void main(String[] args) {
String sentence = "i love you";
List words = Arrays.asList(sentence.split(" "));
for (int i = 0; i < words.size(); ) {
if (words.get(i).equals("love")) {
words.remove(i);
continue;
}
i++;
}
System.out.println(words);
}
然后,运行这段代码,最后,报错了:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at list.AslistMethod.main(AslistMethod.java:12)
错误链的栈底list.AslistMethod.main(AslistMethod.java:12)说的是这一行代码:
words.remove(i);
这个错误让我很迷茫,因为我写这段代码前大概看了一下,Arrays.asList方法返回的是一个ArrayList,咋就不能remove了呢?接下来,由于一个小小的失误,把Arrays.asList的结果赋给了java.util.ArrayList,居然赋值不成功,我立马有种瞎猫碰上死耗子的感觉。然后,就顺着Arrays.asList方法一直点下去,发现此ArrayList非彼ArrayList。Arrays.asList返回的是java.util.Arrays.ArrayList,它只是Arrays的一个内部类。它的代码不长,这里直接贴出来:
private static class ArrayList extends AbstractList
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] array) {
a = Objects.requireNonNull(array);
}
@Override
public int size() {
return a.length;
}
@Override
public Object[] toArray() {
return a.clone();
}
@Override
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
int size = size();
if (a.length < size)
return Arrays.copyOf(this.a, size,
(Class extends T[]>) a.getClass());
System.arraycopy(this.a, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
@Override
public E get(int index) {
return a[index];
}
@Override
public E set(int index, E element) {
E oldValue = a[index];
a[index] = element;
return oldValue;
}
@Override
public int indexOf(Object o) {
if (o==null) {
for (int i=0; i
if (a[i]==null)
return i;
} else {
for (int i=0; i
if (o.equals(a[i]))
return i;
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public Spliterator spliterator() {
return Spliterators.spliterator(a, Spliterator.ORDERED);
}
}
从源码看到,它继承自AbstractList,并且没有remove方法,我找到AbstractList的remove方法:
public E remove(int index) {
throw new UnsupportedOperationException();
}
这就是错误信息的来源。最终知道,Arrays.asList返回的ArrayList并不支持remove,实际上,java.util.Arrays.ArrayList不支持任何形式的元素删除。
总结一下,这次问题的解决确实有点儿瞎猫碰到死耗子的味道,但是,只要我认真看一下报的错误:
at java.util.AbstractList.remove(AbstractList.java:161)
调用java.util.AbstractList的remove方法和我预期的不一样,它就能清晰地告诉我方向。
希望本文所述对大家学习java程序设计有所帮助。