我正在尝试用 Java 创建一个递归列表数据结构,类似于函数式语言中的列表。
我希望它能够实现Iterable,以便可以在for-each 循环中使用。
所以我实现了iterator()创建 的方法Iterator,并且这个循环工作正常(list属于类型RecursiveList<Integer>):
for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
Integer i = it.next();
System.out.println(i);
}
Run Code Online (Sandbox Code Playgroud)
现在我的印象是for (int i : list)基本上只是上面 -loop 的语法糖for,但是当我尝试使用 -each 时for,我收到编译错误:
incompatible types: Object cannot be converted to int
Run Code Online (Sandbox Code Playgroud)
我一生都无法弄清楚为什么它不起作用。这是相关代码:
import java.util.*;
class RecursiveList<T> implements Iterable {
private T head;
private RecursiveList<T> tail;
// head and tail are null if and only if …Run Code Online (Sandbox Code Playgroud)