/** * {@inheritDoc} * * <p>This implementation always throws an * {@code UnsupportedOperationException}. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { throw new UnsupportedOperationException(); }
当时纳闷,怎么回事,这里什么也没做。只要调它就抛异常了,然后想想,我们平时使用的都是ArrayList,而这个是一个抽象类,估计这些方法是必须由子类重写的方法,想必,天天用的ArrayList就继承此类了,继续跟源码.有如下:
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
那为什么我跟进去的不是ArrayList,而是AbstractList??原来,我这个List是通过
Arrays.asLisvt()去转换一个数组而来。再检查了一下源码,果然啊,问题找到了,就好解决了。
1:要么把这个AbstractList转换成ArrayList,
2:要么用迭代器模式,用迭代器模式操作集合,提供了更灵活强大的操作