0

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.

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

I also know that syntax, but that's not what I am searching for.
Then explain yourself better. Do you expect us to both give you free advice and read your mind?
"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?" That's what it says in my question and that's what I'm looking for. Is there a way or is the shortest way really to make the new statement inline?
Well I provided the shortest possible way, since it's still an array, but the compiler just handles the syntax.
Well, technically he did. But the thing is that my constructor takes three arrays of the same kind while Kayaman's solution unfortunately only works if there was only one.
|
0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.