//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、泛型或迭代器,但我认为我做了正确的事情。
这里缺少和/或错误什么?这不是我的完整代码,但我遗漏的其他所有内容都有效。上面的代码片段中某个地方有问题。我遵循的一个示例与我自己的代码或多或少是 1:1,但我的代码似乎不起作用。
最佳答案
问题是你的内部类 ArrIterator
正在重新定义另一个泛型类型参数 <E>
当它仍在外部类的范围内时,Bag
。这会导致新的E
不匹配旧的E
.
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.
删除E
的重新声明在你的内部类(Class)中ArrIterator
并让它extends
子句使用 E
已经在范围内。
public class ArrIterator implements Iterator<E> {
然后你的iterator()
方法不必返回通用 ArrIterator
.
public Iterator<E> iterator() {
return new ArrIterator(this);
}
还有,你的hasNext
迭代器中的方法应返回 boolean
匹配 Iterator
界面。
关于java - Java中Iterable的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22925268/