Java - 将数组直接传递给构造函数,而不是作为变量
Java - Passing an array directly into the constructor, not as a variable
举个例子:
public class Test {
public void main(String[] args) {
int[] someInts = {1, 2, 5};
new Dummy(1, someInts, "Hello"); //works
new Dummy(1, new int[] {1, 2, 5}, "Hello"); //works
new Dummy(1, {1, 2, 5}, "Hello"); //fails
new Dummy(1, [1, 2, 5], "Hello"); //fails
}
public class Dummy {
Dummy(int someNumber, int[] someArray, String message) {
}
}
}
对于两个失败的行,Eclipse 说:"The constructor Test.Dummy(int, int, int, int, String) is undefined"
首先,我不明白为什么它不能将数组识别为数组(仅在失败的行中)。
其次,为什么我不能直接将数组传递给构造函数,而是必须创建一个变量来传递它?
第三,有没有一种方法可以创建一个构造函数,它采用类似该行的内容,这意味着没有变量或 new int[] {...}
语句?
如果有人知道在标题中表达这个的更好方法,请随时改进它。
new Dummy(1, {1, 2, 5}, "Hello");
,数组初始化只能使用{}
语法。使用 new Dummy(1,new int[] {1, 2, 5}, "Hello");
如前所述,这就是一般情况下创建数组文字的方式。
您可以用 int... array
varargs 参数替换数组,但是您需要将其作为最后一个参数。
Dummy(int someNumber, String message, int... someArray) {}
new Dummy(1, "Hello", 1, 2, 5);
举个例子:
public class Test {
public void main(String[] args) {
int[] someInts = {1, 2, 5};
new Dummy(1, someInts, "Hello"); //works
new Dummy(1, new int[] {1, 2, 5}, "Hello"); //works
new Dummy(1, {1, 2, 5}, "Hello"); //fails
new Dummy(1, [1, 2, 5], "Hello"); //fails
}
public class Dummy {
Dummy(int someNumber, int[] someArray, String message) {
}
}
}
对于两个失败的行,Eclipse 说:"The constructor Test.Dummy(int, int, int, int, String) is undefined"
首先,我不明白为什么它不能将数组识别为数组(仅在失败的行中)。
其次,为什么我不能直接将数组传递给构造函数,而是必须创建一个变量来传递它?
第三,有没有一种方法可以创建一个构造函数,它采用类似该行的内容,这意味着没有变量或 new int[] {...}
语句?
如果有人知道在标题中表达这个的更好方法,请随时改进它。
new Dummy(1, {1, 2, 5}, "Hello");
,数组初始化只能使用{}
语法。使用 new Dummy(1,new int[] {1, 2, 5}, "Hello");
如前所述,这就是一般情况下创建数组文字的方式。
您可以用 int... array
varargs 参数替换数组,但是您需要将其作为最后一个参数。
Dummy(int someNumber, String message, int... someArray) {}
new Dummy(1, "Hello", 1, 2, 5);