首先给出一段代码:
public class AslistMethod {
public static void main(String[] args) {
String sentence = "i love you";
List<String> 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<E> extends AbstractList<E>
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> 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<a.length; i++)
if (a[i]==null)
return i;
} else {
for (int i=0; i<a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public Spliterator<E> 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方法和我预期的不一样,它就能清晰地告诉我方向。我仅仅想对自己说,不要急,不然未来来不了。如今也过不好。