記一個關於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