2015-01-05 96 views
4

無法弄清楚爲什麼這是循環無限。Java迭代器無限循環

public void DLCCheck(IconSet iconSet) { 
    Log.d(TAG, "Got dlc check. Looking to see if we need to remove any notes from the current list."); 
    int foundCount = 0; 
    for(Iterator<Item> i = mItemList.iterator(); i.hasNext();) { 
     if(i instanceof NoteItem && ((NoteItem) i).getIconSet() == iconSet) { 
      i.remove(); 
      foundCount++; 
     } 
    } 
    Log.d(TAG, "Finished searching. Found " + foundCount + "notes in the current list to delete."); 
    //notifyDataSetChanged(); 
    //EventBus.getDefault().post(new MoveNoteListOut()); 
} 

當hasNext返回false時,不應該停止迭代嗎?這個列表中只有6個項目,但它永遠循環。

+0

這實際上是有幫助的。爲什麼這個題外話? – dan

回答

11

你永遠不會打電話給i.next()。另外,iinstanceof Iterator,所以i instanceof NoteItem永遠不會是true。您應該閱讀i.next()中的數據並根據您的條件評估此類元素。

這在代碼中應該如何:

for(Iterator<Item> i = mItemList.iterator(); i.hasNext();) { 
    Item item = i.next(); 
    if(item instanceof NoteItem && ((NoteItem) item).getIconSet() == iconSet) { 
           //here ---------------------------^^ 
           //not sure what type returns getIconSet 
           //but if it's not a primitive then you should use equals 
     i.remove(); 
     foundCount++; 
    } 
} 
+0

謝謝!爲什麼我應該使用equals方法,如果它不是基本的? – AnnonAshera

+0

因爲在對象引用中'=='檢查引用的等同性,而'equals'則計算引用狀態的相等性。這裏有更好的解釋:[我如何比較Java中的字符串?](http://stackoverflow.com/q/513832/1065197) –

+0

啊是的。謝謝。 – AnnonAshera