Iterator调用remove()时抛出异常 java.lang.IllegalStateException

转载请注明出处WangYuheng’s Blog

[问题]

Iterator remove()时抛出异常 java.lang.IllegalStateException

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
Iterator<String> it = list.iterator();
int i =3;
while(it.hasNext()) {
//                it.next();
    if (i-->1) {
        it.remove();
    }
}
System.out.println(list.size());

[原因]

没有调用next() 方法

[怎么发现的]

跟踪代码,查看Iterator.class源码,在源码注释中看到

/**
 * 
 * Removes from the underlying collection the last element returned by the
 * iterator (optional operation).  This method can be called only once per
 * call to <tt>next</tt>.  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 <tt>remove</tt>
 *          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();

[修复]

先调用next()方法,再调用remove()方法

[我导致的]

是的

[解决Bug的时间]

3分钟

[教训]

需要熟悉Iterator使用方法及设计原理