我想创建一个自己的迭代器,它循环访问由MenuItems组成的Menu对象的ArrayList。每个menuItem有4个值。我试图遍历arrayList,只返回具有类别值MainDish的值。我一直得到一个无限循环。它必须位于实现迭代器接口的迭代器的next()方法中,但是我不能在我的生活中找到错误的位置。它必须是我增加currentIndex的位置,但无法弄清楚。任何和所有的帮助表示赞赏。通过ArrayList迭代的无限循环Java
迭代器类:
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
}
}
这里是我的主:
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)'< - 这里。应该是'=='。或者只是“如果(找到)”。 – fge
为什么要使用迭代器?您可以更简单地使用for循环的用户吗? – TheBrenny
啊,把它改为只要(发现)有帮助,但现在我得到了没有这样的元素例外,我推它作为默认情况。想法? –