簡體   English   中英

通過ArrayList Java進行無限循環迭代

[英]Infinite Loop iterating through ArrayList Java

我試圖創建自己的迭代器,該迭代器遍歷由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()); 
     } 
  }

無論當前項目是否匹配,next()方法都需要使currentIndex遞增。 按照書面規定,一旦達到實際匹配,就會出現無限循環。

順便說一句,按照書面規定,沒有理由不使用常規迭代器並檢查結果。 如果您真正想要的是一個可以直接跳到下一個匹配項的迭代器,則需要在next()方法內添加一個增量循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM