一日早上起来赶工。,碰到一奇怪的问题,我要对一个List进行添加操作,可是,无论我怎么添加,始终报java.lang.UnsupportedOperationException异常。这就奇了怪了,对List进行添加操作,我几乎每天都要做,今天就xie了门了。于是,我跟了下jdk源码,发现抛的这个异常是直接在一个AbstractList类里,方法如下:
当时纳闷,怎么回事,这里什么也没做。只要调它就抛异常了,然后想想,我们平时使用的都是ArrayList,而这个是一个抽象类,估计这些方法是必须由子类重写的方法,想必,天天用的ArrayList就继承此类了,继续跟源码.有如下:
那为什么我跟进去的不是ArrayList,而是AbstractList??原来,我这个List是通过
Arrays.asLisvt()去转换一个数组而来。再检查了一下源码,果然啊,问题找到了,就好解决了。
1:要么把这个AbstractList转换成ArrayList,
2:要么用迭代器模式,用迭代器模式操作集合,提供了更灵活强大的操作
/**
* {@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:要么用迭代器模式,用迭代器模式操作集合,提供了更灵活强大的操作