最近在做通用數據收集接口.由於業務比較複雜,數據無法在數據庫中完成分組和排序.只要在內存中進行.需要對java的List進行迭代刪除.當時條件反射的用了java的foreach循環.在循環中用了remove操作.代碼大致如下:
List<TopIndex> topIndexes=....
for(TopIndex topIndexe : topIndexes){
//....
topIndexes.remove(topIndexe );
//...
}
很自然出現了不一致的數據,但是沒有throw異常.經過過跟蹤,發現了問題.於是將foreach循環改寫爲:
for(Iterator<TopIndex> it=topIndexes.iterator();it.hasNext();){
//....
topIndexe=it.next();
topIndexes.remove(topIndexe );
//...
}.
這次拋出異常了,異常信息提示非同步操作.我立馬想到刪除操作應該用於迭代器的remove方法.否者會拋出異常.於是改寫了代碼:
for(Iterator<TopIndex> it=topIndexes.iterator();it.hasNext();){
//....
it.next();
//...........
it.remove();
//...
}.
而後,程序正確運行.通過這次我bug排除,我認識到.不能僅僅記得書本上的理論,教條.更應動手實踐,積累經驗.形成條件反射.
在發現問題,解決問題後,需要總結,下次遇到同樣的問題,就可以迎刃而解了.
本次總結如下: java foreach只能用於只讀的情況.如果需要刪除操作,請用迭代器或者直接遍歷List.