Iterator迭代器remove元素出现UnsupportedOperationException异常
今天在学习迭代器时,发现remove元素时出现UnsupportedOperationException异常。查阅别人的博客发现自己犯了一个错误。
由于我的list是有Arrays.asList(“kelly”,“jerry”,“helen”)得到的,这样得到的list跟java.util.arraylist中的list是不一样的。Arrays.asList(“kelly”,“jerry”,“helen”)返回的是Arrays内部的list,而不是java.util.ArrayList。
Arrays的内部类ArrayList和java.util.ArrayList都是继承AbstractList,remove、add等方法AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。java.util.ArrayList重新了这些方法,而Arrays的内部类ArrayList没有重写,所以会抛出异常。
//AbstractList的源码
public E remove(int index) {
throw new UnsupportedOperationException();
}
在remove元素之前必须调用next方法,不然会出现 **java.lang.IllegalStateException
**异常
参考博客:https://blog.csdn.net/qq_39416311/article/details/83688591
来源:CSDN
作者:qq_42008471
链接:https://blog.csdn.net/qq_42008471/article/details/103810952