Eclipse compile error shown incorrectly (Can only iterate over an array or an instance of java.lang.Iterable)

351 Views Asked by At

I'm experiencing a really weird issue in Eclipse (Photon 4.8). I have some code that uses the for (Object x : ObjectList){} logic and all of a sudden it's throwing a compile error on me.

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

So as to keep it super simple, I wrote the following as a test in my class

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);
}

That block also throws the same error (on the "tmp" object). I've restarted Eclipse several times and done a clean/rebuild. My Java compiler is set to 1.8 which is a change that i made about a week ago from 1.6. But it's been compiling fine the past week with no errors. Just saw this pop up today out of the blue.

Seems like a bug in the Eclipse compiler, but I'm not sure how to resolve it. Any help would be greatly appreciated.

Adding "Minimal, Complete and Verifiable Example" below

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);
        }
    }
}

The above class throws the following compile error for "tmp"

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

There are 1 best solutions below

1
AlanK On

You don't need to define a new iterator:

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