今天在使用Iterator的时候被一个问题困扰了很久,最后通过一步步的找错终于找出了错误,原因是忽视了一个小问题,现在先来说一下我的操作:
while(it.hasNext()){
Map<String,Object> product=it.next()
;
if(product.containsKey("pid")){
int value=Integer.parseInt(String.valueOf(product.get("pid")));
if(value==pid){
shoppingList.remove(it.next()
);
}
}
}
这是我的代码,相信大家都可以看懂了,但是奇怪的是运行这段代码以后,总是报NoSuchElementException
异常,为什么呢?找了很久都没找出来,最后发现了问题的所在, 看到上面的红色标记没有,这里有两个it.next();我们来看一下这个方法在API中的说明:
next
E next()
Returns the next element in the iteration.
Returns:
the next element in the iteration.
Throws:
NoSuchElementException - iteration has no more elements.
现在应该知道问题的所在了吧,第一个it.next()后再去it.next()就不是原来想要的了,也就是说it.next()后这个it就指向了下一个对象,所以第二个it.next() 应该换成product,对于Iterator处理,建议新建一个变量保存it.next()的值,后面就直接对这个值操作就行了。
<!-- Generated by javadoc (build 1.6.0) on Wed Nov 29 02:21:55 PST 2006 -->
<noscript></noscript>