I am learning java and I did not see anything in the documentation about this. Is it possible to initialize only part of an array, with a bunch of different strings like so in one line:
String[] anArray = new String[20] {"water", "shovel", "berries", "stick", "stone", "seed", "axe"};
Only 7 spaces in the array are filled, and the rest can be initialized later? Is this possible? I find manually filling each space anArray[i]
cumbersome. I also do not want to use an ArrayList, for reasons elsewhere in my code.
Help appreciated!
No you cannot do this the way you are trying. This is because (According to the docs tutorial) This way of declaring an array:
String[] array = {"Apple", "Orange"};
is a shortcut of doing:
String[] array = new String[2];
array[0] = "Apple";
array[1] = "Orange";
In the tutorial it says about the first way:
Here the length of the array is determined by the number of values provided between braces and separated by commas.
It is not valid to both declare the size and then try to do the shortcut syntax of declaring an array
. (The actual warning given is: Cannot define dimension expressions when an array initializer is provided
)
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