jamesrappazzo
jamesrappazzo

Reputation: 71

Infinite Loop iterating through ArrayList Java

I am trying to create my own iterator that loops through an ArrayList of Menu objects which is comprised of MenuItems. Each menuItem has 4 values. I am trying to iterate through the arrayList and only return the values that have the category value MainDish. I keep getting an infinite loop. It has to be in the next() method of my iterator which implements the iterator interface, but I cannot for the life of me find where the error is. It has to be the location of where I increment currentIndex, but can't figure it out. Any and all help is appreciated.

Iterator Class:

package menu;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;


public class ItemIterator implements Iterator<MenuItem> {
private ArrayList<MenuItem> menuList;
private int currentIndex;
private String type;

public ItemIterator(ArrayList<MenuItem> menuList, String type) {
    this.menuList = menuList;
    this.type = type;
    }

@Override
public boolean hasNext() {
    return !(menuList.size() == currentIndex);
}

@Override
public MenuItem next() {

boolean found = false;

    if(hasNext() && !found)
        if(menuList.get(currentIndex).getCategory().equals(type))   
            found = true;
        else
            currentIndex++;         


    if(found = true)
        return menuList.get(currentIndex);
    else
        throw new NoSuchElementException();
    }   


@Override
public void remove() {
    // TODO Auto-generated method stub

}

 }

here is my main:

     public static void main(String[] args) {


    MenuItem item1 = new MenuItem("burger", mainDish, false, 10);
    MenuItem item2 = new MenuItem("sandwhich", appetizer, true, 5);

    Menu newMenu = new Menu();

    newMenu.add(item1);
    newMenu.add(item2);




     Iterator<MenuItem> itr = newMenu.getMenuIterator(); 
     System.out.println("ALL MENU ITEMS"); 


     while (itr.hasNext()) 
     { 
     System.out.println(itr.next()); 
     } 

    itr = newMenu.getItemIterator(mainDish); 
     System.out.println("ALL MAIN DISH ITEMS"); 

     while (itr.hasNext()) 
     { 
     System.out.println(itr.next()); 
     } 
  }

Upvotes: 0

Views: 3226

Answers (1)

Warren Dew
Warren Dew

Reputation: 8938

The next() method needs to increment currentIndex whether or not the current item is a match. As written, you get an infinite loop as soon as you reach an actual match.

Incidentally, as written, there's no reason not to use the regular iterator and check the result. If what you really want is an iterator that skips ahead to the next match, you'll need to add an increment loop inside the next() method.

Upvotes: 1

Related Questions