【问题标题】:Eclipse compile error shown incorrectly (Can only iterate over an array or an instance of java.lang.Iterable)Eclipse 编译错误显示不正确(只能迭代数组或 java.lang.Iterable 的实例)
【发布时间】:2019-02-18 13:47:24
【问题描述】:

我在 Eclipse (Photon 4.8) 中遇到了一个非常奇怪的问题。我有一些使用 for (Object x : ObjectList){} 逻辑的代码,突然之间它向我抛出了编译错误。

Can only iterate over an array or an instance of java.lang.Iterable

为了保持超级简单,我在课堂上写了以下内容作为测试

ArrayList<String> tmp = new ArrayList<String>();
tmp.add("making sure there's something here");
tmp.add("and again...just for the heck of it");
for(String x : tmp) {
    System.out.println(x);
}

该块也会引发相同的错误(在“tmp”对象上)。我已经多次重新启动 Eclipse 并完成了清理/重建。我的 Java 编译器设置为 1.8,这是我大约一周前从 1.6 所做的更改。但它在过去一周编译得很好,没有错误。今天突然看到这个弹出来了。

似乎是 Eclipse 编译器中的一个错误,但我不确定如何解决它。任何帮助将不胜感激。

在下面添加“最小、完整和可验证的示例”

public class Test { 
    public static void main(String[] args) {
        java.util.ArrayList<String> tmp = new java.util.ArrayList<String>();
        tmp.add("String 1");
        tmp.add("String 2");
        for(String x : tmp) {
            System.out.println(x);
        }
    }
}

上面的类为“tmp”抛出以下编译错误

Can only iterate over an array or an instance of java.lang.Iterable

【问题讨论】:

  • 迭代器不是可迭代的
  • 那个错误是正确的。 Iterator 不是 Iterable
  • 为什么要责怪 Eclipse 或 Java?请理解,99.99% 的错误是你的,最好一开始就假设是这样
  • 您可以使用tmp.forEach(System.out::println)(Java 8 起)。
  • 呃..我不喜欢把 Iterator 放在里面。我编辑了它(在我上面的帖子和我的代码中)。即使针对实现了 Iterable 接口的 ArrayList 对象,它也会抛出相同的错误。

标签: java java-8 eclipse-photon


【解决方案1】:

您不需要定义新的迭代器:

ArrayList<String> tmp = new ArrayList<String>();
tmp.add("making sure there's something here");
tmp.add("and again...just for the heck of it");
for(String x : tmp) {
    System.out.println(x);
}

>> making sure there's something here
>> and again...just for the heck of it

【讨论】:

  • 是的,这就是我最初所做的。这现在在 Eclipse 中引发编译错误。因此我认为存在某种错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-20
  • 2014-05-23
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
相关资源
最近更新 更多