我正在尝试创建自己的迭代器,该迭代器循环遍历由 MenuItems 组成的 Menu 对象的 ArrayList。每个 menuItem 有 4 个值。我试图迭代 arrayList 并仅返回具有类别值 MainDish 的值。我不断陷入无限循环。它必须位于实现迭代器接口(interface)的迭代器的 next() 方法中,但我一生都无法找到错误所在。它必须是我增加 currentIndex 的位置,但无法弄清楚。感谢任何和所有的帮助。
迭代器类:
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());
}
}
最佳答案
无论当前项是否匹配,next() 方法都需要增加 currentIndex。正如所写,一旦达到实际匹配,您就会进入无限循环。
顺便说一句,正如所写,没有理由不使用常规迭代器并检查结果。如果您真正想要的是一个向前跳到下一个匹配项的迭代器,则需要在 next() 方法中添加一个增量循环。
关于java - Java 无限循环遍历 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21926407/