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
?
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.
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
Is it guaranteed that the elements will be always inserted in the same order I've typed on the initialization?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With