开发者

Java Var-args and enhanced for loop compiler error

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, i is 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 over Iterable instances and arrays - not single values. You should just write:

System.out.println(i);

as there's bound to just be one value.


In the second go() method, you're trying to iterate over an int, not an array of ints (which is what the varargs break down to.) Since you can't meaningfully iterate over an int, the compiler complains.


You can't iterate over a single integer. It worked for your method using varargs input because it's an array of integers, equivalent to an int[] argument.

You can simply use this:

static void go(int i){
    System.out.println("In 2");

    System.out.println(i);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜