1

I am trying to add an array of integers to an ArrayList as follows, which does not work:

ArrayList<int[]> myAL = new ArrayList<int[]>(); myAL.add({2,3}); 

however, adding it by reference works:

ArrayList<int[]> myAL = new ArrayList<int[]>(); int[] id = {2,3}; myAL.add(id); 

I believe you can add simple integers to ArrayList without reference, so how come you can't add an array without reference.

Thanks,

3
  • 2
    {2,3} it doesn't meaning anonymous object to make it you need myAl.add(new int [] {2,3}); Commented Aug 11, 2013 at 0:00
  • I Think You Can Only Add An Int Array To An ArrayList not its values Commented Aug 11, 2013 at 0:02
  • This question has nothing to do with ArrayList at all, it's just a syntax error. Commented Aug 11, 2013 at 1:15

2 Answers 2

2

You always need the to use the anonymous array syntax when declaring an integer array outside an array declaration. This syntax is described in the Java Language Specification under Array Creation Expressions and shows that the new keyword is used

 ArrayCreationExpression: new PrimitiveType DimExprs Dimsopt new ClassOrInterfaceType DimExprs Dimsopt new PrimitiveType Dims ArrayInitializer new ClassOrInterfaceType Dims ArrayInitializer 

That why

int[] id = {2,3}; // declaration 

is valid syntax, whereas

int[] id; id = {2,3}; // assignment - outside declaration - fails compilation 

is not. Therefore it is necessary to use

myAL.add(new int[]{2,3}); 
Sign up to request clarification or add additional context in comments.

Comments

0

Your {2, 3} is an example of an ArrayInitializer. According to the JLS:

10.6. Array Initializers

"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 first three cases are for declaring variables, and that's not what you are doing. The final case corresponds to what you are trying to do ... create an array instance ... but if you look at the linked section you will see that you need to use the Java new keyword to do this.


So why does the Java syntax not allow you to do this ( myAL.add({2,3}); )?

Well, I think that the primary reason is that {2, 3} is not sufficient to say what type of array should be created ... in all such contexts.

Consider this:

 ArrayList myAL = new ArrayList(); myAL.add({2,3}); 

What kind of array is appropriate here? Should it be an int[]? Or a long[]? Or Integer[]? Or Object[]?

The other thing to remember is that array initializers were part of the Java language in Java 1.0 ... well before the Java language included generic types and limited type inferencing that might (hypothetically) allow the ambiguity to be resolved in a sensible fashion.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.