Enhanced For-Loop在使用自定义集合实现Iterable接口时引发编译错误



我正在尝试在Java中创建递归列表数据结构,类似于函数式语言中的列表。

我希望它实现Iterable,以便它可以在for-each循环中使用。

所以我实现了创建Iteratoriterator()方法,这个循环工作得很好(listRecursiveList<Integer>类型):

for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
Integer i = it.next();
System.out.println(i);
}
现在我的印象是,for (int i : list)基本上只是上面的for-循环的语法糖,但是当我尝试使用for-each时,我得到了一个编译错误:
incompatible types: Object cannot be converted to int

我怎么也弄不明白为什么它不工作。以下是相关代码:

import java.util.*;
class RecursiveList<T> implements Iterable {
private T head;
private RecursiveList<T> tail;
// head and tail are null if and only if the list is empty
// [] = { head = null; tail = null}
// [1,2] = { head = 1; tail = { head = 2; tail = { head = null; tail = null } } }
public RecursiveList() {
this.head = null;
this.tail = null;
}
private RecursiveList(T head, RecursiveList<T> tail) {
this.head = head;
this.tail = tail;
}
public boolean add(T newHead) {
RecursiveList<T> tail = new RecursiveList<T>(this.head, this.tail);
this.head = newHead;
this.tail = tail;
return true;
}
public Iterator<T> iterator() {
RecursiveList<T> init = this;
return new Iterator<T>() {
private RecursiveList<T> list = init;
public boolean hasNext() {
return list.head != null;
}
public T next() {
T ret = list.head;
if (ret == null) throw new NoSuchElementException();
list = list.tail;
return ret;
}
}
}
}
class Main {
public static void main(String[] args) {
RecursiveList<Integer> list = new RecursiveList<Integer>();
list.add(1);
list.add(2);
list.add(3);
// works:
for(Iterator<Integer> it = list.iterator(); it.hasNext();) {
Integer i = it.next();
System.out.println(i);
}
// output:
// 3
// 2
// 1
// doesn't work:
// for (int i : list) System.out.println(i);
}
}

让我觉得真正愚蠢的是我的IDE也抓住了这个问题,并强调list给出了相同的错误信息,所以我如何编写我缺少的类型一定有明显的错误,我只是无法想象发生了什么,因为iterator()似乎成功地创建了一个Iterator实例,基于更详细的循环工作。

InterfaceIterable是通用的,但是您的自定义Collection实现了行类型的iterable,这实际上是Iterable<Object>。因此,在增强的for-循环中从集合中检索的元素被视为类型为Object

您需要将集合的声明更改为:

class RecursiveList<T> implements Iterable<T>

相关内容

最新更新