【问题标题】:Infinite Loop iterating through ArrayList Java无限循环遍历 ArrayList Java
【发布时间】:2014-03-22 11:51:24
【问题描述】:

我正在尝试创建自己的迭代器,该迭代器循环遍历由 MenuItems 组成的 Menu 对象的 ArrayList。每个 menuItem 有 4 个值。我正在尝试遍历 arrayList 并仅返回具有类别值 MainDish 的值。我一直在无限循环。它必须在实现迭代器接口的迭代器的 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()); 
     } 
  }

【问题讨论】:

  • if(found = true) ==。或者只是if (found)
  • 为什么要使用迭代器?您可以使用 for 循环更简单地完成它吗?
  • 啊,将其更改为 if(found) 有帮助,但现在我得到了 no such element 异常,我将其作为默认情况推送。想法?

标签: java loops arraylist iterator infinite


【解决方案1】:

无论当前项是否匹配,next() 方法都需要增加 currentIndex。正如所写,一旦达到实际匹配,您就会得到一个无限循环。

顺便说一句,正如所写,没有理由不使用常规迭代器并检查结果。如果你真正想要的是一个向前跳到下一个匹配的迭代器,你需要在 next() 方法中添加一个增量循环。

【讨论】:

  • 我现在得到没有这样的元素异常,我把它作为默认情况。
  • 正如你所写的那样,只要当前元素不匹配并且你调用 next(),你就会得到 NoSuchElementException。
  • 我想我的下一个任务是找出循环结构的去向
  • 我似乎无法弄清楚如何放置循环。
  • 您可以先将if(hasNext() &amp;&amp; !found) 替换为while(hasNext() &amp;&amp; !found)。但是,当迭代器位于最后一场比赛之后但在结束之前的某个点时,您仍然需要避免抛出 NoSuchElementException。
猜你喜欢
  • 2013-04-05
  • 2020-06-15
  • 1970-01-01
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多