【问题标题】:Java Iterator Infinite Loop [closed]Java迭代器无限循环[关闭]
【发布时间】:2015-03-02 15:18:58
【问题描述】:

不知道为什么会无限循环。

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 个项目,但它会永远循环。

【问题讨论】:

  • 这实际上很有帮助。为什么这是题外话??

标签: java list loops iterator iteration


【解决方案1】:

你永远不会打电话给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++;
     }
}

【讨论】:

  • 谢谢!如果不是原始方法,我为什么要使用 equals 方法?
  • 因为在对象引用中== 检查引用的相等性,而equals 评估引用状态的相等性。在这里可以更好地解释:How do I compare strings in Java?
猜你喜欢
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 2014-10-28
  • 2017-05-02
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多