我为类MyList
写了一个自定义迭代器,它看起来像这样:
private class MyListIterator implements Iterator<ListItem> {
// Constructor
public MyListIterator() {
nextElement = head;
}
@Override
public ListItem next() {
...
}
然后在类MyList
中创建一个新的MyListIterator
,如下所示:
@Override
public Iterator<ListItem> iterator() {
MyListIterator iterator = new MyListIterator();
return iterator;
}
最后我尝试遍历期望MyList
的ListItem
对象:
MyList list = new MyList();
for (ListItem item : list ) {
System.out.println(item.value);
}
但是我收到不兼容类型错误,因为迭代器返回Object
类型而不是ListItem
。我该如何解决?
编辑:MyList
实现MyListInterface
:
public interface MyListInterface<T extends Comparable<T>> extends Iterable<T> {
public Iterator<T> iterator();
}
但是我不允许在MyListInterface
中进行任何更改
private class ListItem {
Comparable value;
ListItem previous;
ListItem next;
public ListItem(Comparable value) {
this.value = value;
}
}
您的MyList
类implements Iterable
,而不是implements Iterable<ListItem>
。编译器会为此警告您。注意警告。
我假设您错误地写了MyList implements MyListInterface {
,却忘记了添加通用参数。这意味着您使用的是原始类型,应该not