java - 增强的 For-Loop 在自定义集合实现 Iterable 接口(interface)时引发编译错误

标签 java collections iterator iterable

我正在尝试用 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/

相关文章:

java - 为什么 Guava 抽象多重集不公开?

java - 维护过滤后的ObservableList最基本的方法是什么?

C++ 迭代器 : Can iterators to an abstract class be implemented as a nested class?

c++ - std::map::iterators post increment 的奇怪行为

java - 玩!集合(即集合或列表)字段中的 Morphia 查询

c++ - 如何在 STL 算法上接收字符串迭代器

java - 将 void** 指针转换为等效的 Java 类型

java - 在 Java 中为 Garage band 构建 sysex 消息

java - 如何对 LinkedList<String> 进行排序?

python - 在 python 中为非空集合返回 bool 值的推荐方法是什么?