Please explain why the following code snippet fails to compile:
public class ScjpTest{
static void go(int... i){
System.out.println("In 1");
for (int x : i){
System.out.println(x);
}
}
static void go(int i){
System.out.println("In 2");
for (int x : i){
System.out.println(x);
}
}
public static void main(String[] args){
go(1);
go(1,2);
go(1,2,3);
}
}
I was testing to see which instance of go() will be called but it is failing with the following error:
ScjpTest.java:16: foreach not applicable to expression type
for (int x : i){
^
1 error
I cant for the life of me work out what is wrong with the enhanced for loop.
Thanks
In the first overload,
iis an array of integers. That’s how you can iterate over it. In the second overload, it’s just a single integer value. The enhanced for loop only works overIterableinstances and arrays – not single values. You should just write:as there’s bound to just be one value.