Iterator java.util.NoSuchElementException
场景:使用Iterator引起的java.util.NoSuchElementException异常
使用Iterator引起的java.util.NoSuchElementException错误
使用Iterator引起的java.util.NoSuchElementException错误
今天在使用Iterator时写了如下代码:
for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { HashMap hmap = new HashMap() ; hmap.put("file";, iter.next()); hmap.put("state";, (String)map.get(iter.next())); listItem.add(hmap); }
运行发现报错:java.util.NoSuchElementException
检查发现是2次使用了Iterator.next() 方法,导致边界溢出
做如下修改解决
另要注意:当iterator中的elements个数为偶数是不会报错的
for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { HashMap hmap = new HashMap() ; String nextElement = (String)iter.next(); hmap.put("file";, nextElement); hmap.put("state";, (String)map.get(nextElement)); listItem.add(hmap); }