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"
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?
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.
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.