簡體   English   中英

如何使用每種類型的循環迭代通用列表

[英]How Do I Iterate Generic List Using For Each Type For Loop

我已經獲得了一個創建列表的列表,我可以使用'for each'類型的'for'循環遍歷列表,而不是為Iterator構建一個構造函數。 問題是當我下面的代碼時,我得到錯誤消息“只能迭代數組或java.lang.Iterable的實例”。 這是代碼:

public static void main(String[] args) {
    GList<InnerList> list = new GList<InnerList>(); 
    GList<InnerList> numList = new GList<InnerList>();
    InnerList lst = new InnerList ();
    Scanner sc = new Scanner(System.in);
    String answer;      
    while (true){
        System.out.println ("Do you want to create a list (y/n)? ");
        answer = sc.next();
        if (answer.equals("y")){
            System.out.println("Enter the name of the list: ");
            answer = sc.next();
            lst.setName(answer);
            if (list.isEmpty()== true){
                list.insertFirstItem(lst);
            }
            else {
                list.insertNext(lst);
            }           
        }               
        while (true){
            System.out.println("Do you want to enter a number (y/n)?");
            answer = sc.next();
            if (answer.equals("y")){
                System.out.println("Enter Number: ");
                answer = sc.next();
                try {
                    int num1 = Integer.parseInt(answer);
                    lst.setInner(num1);
                    if (list.isEmpty() == true){
                        list.insertFirstItem(lst);  
                    }
                    else {
                        list.insertNext(lst);
                    }                       
                }
                catch (NumberFormatException e){
                    System.out.println("You must enter an number! " + e);
                    sc.close();
                }                       
            }
            return;
        }       
    }
    for (GList<InnerList> ilName : list){ //here are my error msgs. I also tried replacing GList<InnerList> with 'InnerList' and String. 
        for(GList<InnerList> ilInts : list){
            System.out.println(ilName);
            System.out.println(ilInts);
        }
    }       
}   

有人可以幫我理解為什么集合應該可迭代時,為什么GList不被視為java.lang.iterable的實例嗎?

謝謝。

它不被視為java.lang.Iterable的實例,因為它沒有實現接口java.lang.Iterable 就如此容易。 將其聲明更改為

public class GList<T> implements Iterable<T>

你會很樂意使用它的foreach循環。 但是因為listGList<InnerList>一個實例,並且因為GList<InnerList>包含InnerList實例(至少,我猜是這樣),所以循環應該是:

for (InnerList innerList : list) {
    ...
}

這是語法錯誤,coorect語法是,

for(InnerList ilName : GList) {
   for(InnerList ilInts : GList) {
     System.out.println(ilName);
     System.out.println(ilInts);
    }
}  

希望這可以幫助

暫無
暫無

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

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