4

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.

AnnonAshera
  • 399
  • 1
  • 4
  • 12

1 Answers1

11

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++;
     }
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Thank you! Why should I use equals method if its not a primative? – AnnonAshera Jan 05 '15 at 05:06
  • 1
    Because in object references `==` checks for equality of references, while `equals` evaluates equality of the state of the references. This is better explained here: [How do I compare strings in Java?](http://stackoverflow.com/q/513832/1065197) – Luiggi Mendoza Jan 05 '15 at 05:08