Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an initialized Array retain its order?

Say that I initialize an Array somewhat like this:

int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

Is it guaranteed that the elements will be always inserted in the same order I've typed on the initialization? E.g.: 100,200,300,400,500,600,700,...,1000?

like image 907
Mauker Avatar asked Jan 11 '16 23:01

Mauker


4 Answers

Yes this is guaranteed by the specification (see JLS 10.6):

The variable initializers immediately enclosed by the braces of the array initializer are then executed from left to right in the textual order they occur in the source code. The n'th variable initializer specifies the value of the n-1'th array component.

like image 148
Alexis C. Avatar answered Oct 18 '22 03:10

Alexis C.


Short answer: Yes, if you initialize it like that, they will be in the order as initialized.

See the JLS about that:

The variable initializers immediately enclosed by the braces of the array initializer are then executed from left to right in the textual order they occur in the source code. The n'th variable initializer specifies the value of the n-1'th array component

https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.6

like image 24
dunni Avatar answered Oct 18 '22 02:10

dunni


Is it guaranteed that the elements will be always inserted in the same order I've typed on the initialization?

Yes

like image 3
jmj Avatar answered Oct 18 '22 03:10

jmj


YES!

The code you posted is identical to this :

int[] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };

What this does, is create an array of integers, where 100 goes at position 0, 200 to position 1, 300 to position 2 , 400 to position 3, etc.

This works the same for every array every time!

like image 1
John Slegers Avatar answered Oct 18 '22 02:10

John Slegers