记一个关于java Iterator的bug
最近开发数据库时,需要遍历一张表的每一行。很自然地选择了迭代器:
Iterator<Row> iterator = currentTable.iterator();
while(iterator.hasNext()){
Row currentRow = iterator.next();
//System.out.println(currentRow);
if(currentRow.getEntries().get(attrNameIndex).compareTo(attrValueEntry)==0){
deleteEntries.add(currentRow.getEntries().get(primaryIndex));
}
}
这一段代码是没有bug的,我最初是这么写的:
while(currentTable.iterator().hasNext()){
Row currentRow = currentTable.iterator().next();
//System.out.println(currentRow);
if(currentRow.getEntries().get(attrNameIndex).compareTo(attrValueEntry)==0){
deleteEntries.add(currentRow.getEntries().get(primaryIndex));
}
}
这么写会导致无限循环。
总结
迭代器在使用时必须在循环体外获得。否则相当于每一次检查循环终止条件时,重新获得一个迭代器,那么如果这个迭代对象至少有一个元素,hasNext()返回的值永远是true