作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试用 Java 制作递归列表数据结构,类似于函数式语言中的列表。
我希望它实现 Iterable
以便它可以用于 for
-每个循环。
所以我实现了 iterator()
创建 Iterator
的方法,并且此循环工作正常( list
属于 RecursiveList<Integer>
类型):
for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
Integer i = it.next();
System.out.println(i);
}
现在我的印象是for (int i : list)
基本上只是 for
的语法糖- 上面的循环,但是当我尝试使用 for
- 每个,我都遇到了编译错误:
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
具有基于更详细循环工作的正确类型的实例。
最佳答案
接口(interface) Iterable
是通用的,但是您的自定义 Collection 实现了行类型的可迭代,这实际上是 Iterable<Object>
.出于这个原因,从您的集合中检索到的元素位于增强的 for
中。 -loop 被视为 Object
类型.
您需要将集合的声明更改为:
class RecursiveList<T> implements Iterable<T>
关于java - 增强的 For-Loop 在自定义集合实现 Iterable 接口(interface)时引发编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74685521/
我是一名优秀的程序员,十分优秀!