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());
}
}
if(found = true)<-- here. Should be==. Or justif (found).