2013-02-23 28 views
2

我已經被賦予創建列表的列表,我應該能夠遍歷列表使用'for each'類型的'for'循環,與爲Iterator構建構造函數。問題是,當我下面的代碼,我得到錯誤味精「只能遍歷數組或java.lang.Iterable的實例」。下面是代碼:如何迭代通用列表使用for Each類型For循環

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); 
     } 
    }  
} 

有人可以幫助我瞭解爲什麼鏈表本身不被認爲java.lang.iterable的實例時集應迭代?

謝謝。

+0

什麼錯誤它顯示? – 2013-02-23 17:11:40

+0

原始文章中的錯誤是「」只能迭代一個數組或java.lang.Iterable的實例「 – Chris 2013-02-23 17:14:24

回答

9

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

public class GList<T> implements Iterable<T> 

然後你就可以使用foreach循環了。但由於listGList<InnerList>一個實例,因爲GList<InnerList>包含InnerList情況下(至少,我猜是這樣),循環應該是:

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

你是對的,它確實包含InnerList的實例當我向GList添加'implements Iterable '它告訴我「類型GList 必須實現繼承的抽象方法Iterable .iterator()」;這是什麼意思? – Chris 2013-02-23 17:12:05

+1

您必須實現在Iterable接口中聲明的方法:'public Iterator iterator()' 。你是否理解接口的概念?如果是這樣,你應該明白在你實現的接口中聲明的每個方法都必須被實現,否則請閱讀一本好的入門Java書或[Java教程](http:// docs.oracle.com/javase/tutorial/java/concepts/interface.html) – 2013-02-23 17:18:18

+0

I und依據接口的概念,但我們已經獲得了我們允許使用的「唯一」公共方法,公共Iterator 不是其中之一嗎? – Chris 2013-02-23 17:21:52

-2

這是一個語法錯誤和coorect語法是,

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

希望這有助於

+1

這實際上是錯誤的。這不是使用Enhanced For的正確方法。 – Genzer 2013-02-23 17:40:08