关于list的动态删除操作,报异常 ,求解

这样写代码会报错

      List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        Iterator<String>  iterator = list.iterator();
        while(iterator.hasNext()){
//          String s = iterator.next();
//          System.out.println(iterator.next());
            iterator.remove();
        }
        System.out.println(list.size());

 这样不报错

 写道
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String s = iterator.next();
iterator.remove();
}
System.out.println(list.size());

 这样也不报错

 写道
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){

System.out.println(iterator.next());
iterator.remove();
}
System.out.println(list.size());

 这是为什么了,求解
问题补充

magicyyao 写道
你换成Iterable应该就可以

我用的就是这个啊

你可以这么理解,具体游标的位置只是抽象的。

游标:(*号表示游标的位置,它指向a的前面)

  • a b c d

第一次
while(iterator.hasNext()){//游标的右边有东西么?当然有了
//下面这句然后游标往右边移动一个单位 a* b c d (游标*指向a了)
String s = iterator.next();
iterator.remove();//你移除游标指着的,就是a了,因为游标在a那啊 * b c d
}

第二次循环
while(iterator.hasNext()){//游标的右边有东西么?当然有了
//然后游标往右边移动一个单位 b* c d (*指向b了)
String s = iterator.next();
iterator.remove();//你移除,就是b了,因为游标在b那啊 剩下 * c d
}

在刚开始的时候游标在a左边,你不next一次,游标位置上没有东西啊,你怎么remove了?

因为Iterator接口的核心方法next()或者hasNext()
是依赖于迭代器的当前迭代位置的。

你换成Iterable应该就可以

next()返回迭代的下一个元素,hasNext()返回是否存在元素,你可以看下Iterator的API

直接调用remove会出现这个异常:Exception in thread "main" java.lang.IllegalStateException
而这个异常的方法解释是下面的:
IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method.

[code="java"]
/**
*
* Removes from the underlying collection the last element returned by the
* iterator (optional operation). This method can be called only once per
* call to next. The behavior of an iterator is unspecified if
* the underlying collection is modified while the iteration is in
* progress in any way other than by calling this method.
*
* @exception UnsupportedOperationException if the remove
* operation is not supported by this Iterator.

 * @exception IllegalStateException if the <tt>next</tt> method has not
 *        yet been called, or the <tt>remove</tt> method has already
 *        been called after the last call to the <tt>next</tt>
 *        method.
 */
void remove();

[/code]
API中已经有解释,在不调用next方法前,直接调用remove会抛出异常!

iterator.remove();报错了,删除应该不会报错,因为Iterator只能实现集合的迭代显示,它实现了For循环的效果,如果要全部删除可以用 Clear()方法或者用for循环迭代删除。。。