0

我需要创建匿名 int 数组以传递给方法。我不想声明一个变量然后传递该变量,因为它使代码看起来很拥挤。这就是我们可以为整数数组做的事情。

new Box(new Integer[]{1,2,3});

如何用 int 做到这一点?

4

3 回答 3

3

做就是了:

new Box(new int[]{1,2,3});
于 2013-05-20T02:00:43.437 回答
2

如果您已经了解数组内容,则始终可以使用以下方法

public void foo(int... args) {
    for (int arg : args) {
      // do smth with arg.
     }
}


foo(1,2,3,4,5,6,7); //pretty much unlimited arguments can be passed in.


//or you can do the same to a class constructor as well
new Box(1,2,3,4,5,6);

class Box {
  public Box(int... args){
    //loop 
  }
}

希望能帮助到你

于 2013-05-20T02:00:44.317 回答
0

好的。它似乎与问题相同。

new Box(new int[]{1,2,3});

不知道为什么 Eclipse 之前给了我波浪形的红色条。

于 2013-05-20T02:01:34.030 回答