我之所以要创建int数组而不是直接传递一个作为参数?

时间:2016-05-08 04:45:42

标签: java arrays

我能找到的最接近的是这个帖子:

fillna

答案很清楚,你定义了一个int [] tempArray并使用tempArray作为参数。但是,我的问题是为什么我不能直接将int数组写为参数。

代码示例如下:

#header {
background-color:#ffffff;
color:white;
text-align:center;
padding:5px;
}
#navbar {
background-color:#ffffff;
 color:#000000
text-align:left;
padding:5px;
}
#section {
background-color:#ffffff;
width:500px;
float:left;
padding:10px; 
}
#sidebar {
line-height:30px;
background-color:#14004d;
height:300px;
width:200px;
float:right;
padding:5px; 
}
#footer {
background-color:#14004d;
color:#ffffff;
clear:both;
text-align:center;
padding:5px; 
}

3 个答案:

答案 0 :(得分:5)

可以。但这样做的语法需要new int[],因为你不能使用声明提供的语法糖。像,

test.doSomething(new int[] {1, 2, 3});

答案 1 :(得分:3)

如果要这样做,可以使用变量参数。像这样制作test.doSomething()方法:

void doSomething(int... arguments)
{
    // ...
}

然后您可以传递整数而无需新语法。编译器会处理它们。

test.doSomething(1, 2, 3);
test.doSomething(new int[] { 1, 2, 3 });

现在都有效。在方法内部,编译器自动将参数作为数组,因此逻辑也没有变化。

答案 2 :(得分:0)

如果使用正确的语法并将数组直接传递给方法,则会出现任何错误。 它应该像

test.doSomething(new int[] {1, 2, 3});