2014-04-08 62 views
0
//project.java 
import MULTISET; 
public class Bag<E extends Keyed> implements Iterable<E> { 
    //cannot find symbol. symbol: class Iterator. location: class project.Bag<E> 
    public Iterator<E> iterator() { 
     return new ArrIterator(this); 
    } 
    //same error as above   
    public class ArrIterator implements Iterator<E> {  
     Bag<E> arr; 
     int coun;  
     public ArrIterator(Bag<E> arr) { 
      this.arr = arr; 
      this.coun = 0; 
     }  
     public boolean hasNext() { 
      return this.coun < arr.cardinality(); 
     }  
     public E next() { 
      if (!hasNext()) { 
       throw new NoItemException(); 
      } 
      return arr.getArray()[coun+1]; 
     }  
     public void remove() { 
      throw new UnsupportedOperationException(); 
     } 
    }  
} 

//MULTISET.java 
//cannot find symbol. symbol: class Iterator. location: interface MultiSet<E> 
public interface MultiSet<E extends Keyed> extends Iterable<E> { 
    public Iterator<E> iterator(); 
} 

我正在試圖對bag類型做foreach循環,並且我得到了兩個註釋錯誤。我不太熟悉ADT,泛型或迭代器,但我認爲我做了正確的事情。Java中的Iterable的實現

這裏有什麼遺漏和/或錯誤?這不是我完整的代碼,但我遺漏的其他所有東西都可以工作。在上面的代碼片段中有一個問題。我使用我自己的代碼或多或少是1:1的例子,但我似乎並不工作。

+1

將hasNext()的返回類型更改爲布爾值而不是布爾值。 –

+1

只是一個想法:如果你在'ArrIterator'的構造函數中傳遞'Bag',那麼你應該聲明'ArrIterator'是一個'static'類(或者甚至將它移動到一個單獨的編譯單元中)。 –

+0

'coun + 1'應該是next()中的'coun ++',但是爲什麼你想縮寫'count'是一個謎。 – EJP

回答

2

問題是當你的內部類別ArrIterator重新定義了另一個通用類型參數<E>,它仍然在你的外部類Bag的範圍內。這導致新的E不匹配舊的E

根據Section 6.3 of the JLS

The scope of a class's type parameter (§8.1.2) is the type parameter section of the class declaration, the type parameter section of any superclass or superinterface of the class declaration, and the class body.

在你的內部類ArrIterator刪除的E重新申報,並讓其extends子句中使用E已經在範圍之內。

public class ArrIterator implements Iterator<E> {  

然後你iterator()方法沒有返回一個通用ArrIterator

public Iterator<E> iterator() { 
    return new ArrIterator(this); 
} 

而且,你在你的迭代hasNext方法應該返回boolean匹配Iterator接口。

+0

乾杯的解釋,幫助我把我的頭正確的方向。關於你的第二個代碼片段,我得到了同樣的錯誤:Bag中的iterator()無法在Iterable中實現iterator()。返回類型Package.Iterator 與java.util.Iterator 不兼容,其中E,T是類​​型變量。添加'@ Override'也不會改變任何內容。 – gator

+0

@riista你必須做兩個改變。 – EJP

+0

@EJP,我做了rgettman建議的所有更改。 – gator