//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的例子,但我似乎並不工作。
將hasNext()的返回類型更改爲布爾值而不是布爾值。 –
只是一個想法:如果你在'ArrIterator'的構造函數中傳遞'Bag',那麼你應該聲明'ArrIterator'是一個'static'類(或者甚至將它移動到一個單獨的編譯單元中)。 –
'coun + 1'應該是next()中的'coun ++',但是爲什麼你想縮寫'count'是一個謎。 – EJP