2015-01-05 98 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