Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Iterator Infinite Loop [closed]

Can't figure out why this is looping infinitely.

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 this stop iterating when hasNext returns false? There are only 6 items in this list, yet it loops forever.

like image 937
AnnonAshera Avatar asked Dec 20 '22 08:12

AnnonAshera


1 Answers

You're never calling i.next(). Also, i is instanceof Iterator, so i instanceof NoteItem will never be true. You should read the data in i.next() and evaluate such element with your conditions.

This in 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's not a primitive then you should use equals
         i.remove();
         foundCount++;
     }
}
like image 111
Luiggi Mendoza Avatar answered Jan 05 '23 09:01

Luiggi Mendoza