2

I would like to have a collection that holds arrays of integers.

List<int[]> pairs = new ArrayList<>();

in order to add there an element I have to:

int[] newArray = {1, 2};
pairs.add(newArray);

Can someone explain my why the below does not work:

 pairs.add({1,2});

is there any other way to add {1,2} to pairs without creating newArray object?

1

2 Answers 2

4

Most of the time, you'll need to do new int[] { 1, 2 }:

pairs.add( new int[] {1,2} );

The only place that you can avoid the new int[] is when you're declaring a variable of type int[], as you've done with int[] newArray = {1, 2};. It's just a limitation of the language design. In particular, you can read 10.6. Array Initializers in the specification, which states that:

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.

The important thing to take away from that is that { 1, 2 }, is an array initializer, and you can use it in a declaration (int[] newArray = {1, 2};), or in an array creation expression (new int[] { 1, 2 }); you can't use it on its own.

Sign up to request clarification or add additional context in comments.

Comments

1

You got the syntax slightly wrong.
Try this: pairs.add(new int[]{1,2});

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.