1

I can easily create an array like this:

int[] someArray = {1,2,3}

and that's nice. Now, lets say that I want to instantiate a new object of SomeClass and the constructor takes some arrays as parameters, how come I can't do the following?

SomeClass someObject = new SomeClass ({1,2,3},{'h','i'})

How can I initialize the array in the constructor?

3 Answers 3

8

You can do

new SomeClass (new int[] {1,2,3}, new char[] {'h','i'})
Sign up to request clarification or add additional context in comments.

1 Comment

Gah, of course! I had already tried doing it with int[] {1,2,3}.
2

You should do:

SomeClass someObject = new SomeClass (new int[] {1,2,3}, new char[] {'h','i'})

1 Comment

I think the letters were meant to be char
2

The reason why is simply that there is special syntactic sugar to treat this:

int[] someArray = {1,2,3};

as meaning this:

int[] someArray = new int[] {1,2,3};

and no special syntactic sugar for other places where new int[] {1,2,3} might occur.

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.