Endless Loop Java Iterator

It is impossible to understand why this happens endlessly.

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());
}

Shouldn't iteration stop when hasNext returns false? There are only 6 items on this list, but they will forever go in cycles.

+4
source share
1 answer

You never call i.next(). In addition, i- instanceof Iterator, therefore, i instanceof NoteItemnever will be true. You should read the data in i.next()and evaluate this item with your conditions.

This is how the code should be:

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 not a primitive then you should use equals
         i.remove();
         foundCount++;
     }
}
+11
source

Source: https://habr.com/ru/post/1569946/


All Articles