简体   繁体   English

Java - 将数组直接传递给构造函数,而不是作为变量

[英]Java - Passing an array directly into the constructor, not as a variable

Let's take the following example:让我们以下面的例子为例:

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) {

        }
    }
}

For both failing lines, Eclipse says: "The constructor Test.Dummy(int, int, int, int, String) is undefined"对于两条失败的线路,Eclipse 说: “构造函数 Test.Dummy(int, int, int, int, String) 是未定义的”

Firstly, I don't understand why it doesn't recognize the array as an array (in the failing lines only).首先,我不明白为什么它不能将数组识别为数组(仅在失败的行中)。

Secondly, why can I not pass the array directly into the constructor, but instead have to create a variable to pass it?其次,为什么我不能将数组直接传递给构造函数,而是必须创建一个变量来传递它?

And thirdly, is there a way to create a constructor which takes something like that line in question, meaning without a variable or a new int[] {...} statement?第三,有没有办法创建一个构造函数,该构造函数采用类似该行的内容,意味着没有变量或new int[] {...}语句?

If someone knows a better way to formulate this in the title, feel free to improve it.如果有人知道在标题中表述这一点的更好方法,请随时改进它。

As said, that's how you create an array literal in the general case.如前所述,这就是您在一般情况下创建数组文字的方式。

You could replace the array with a int... array varargs parameter, but then you'll need to make it the last parameter.您可以将数组替换为int... array varargs 参数,但随后您需要将其设为最后一个参数。

Dummy(int someNumber, String message, int... someArray) {}
new Dummy(1, "Hello", 1, 2, 5);

new Dummy(1, {1, 2, 5}, "Hello"); , you can only use {} syntax for array initialization . ,您只能使用{}语法进行数组初始化。 use new Dummy(1,new int[] {1, 2, 5}, "Hello");使用new Dummy(1,new int[] {1, 2, 5}, "Hello");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM