4

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!

0

4 Answers 4

3

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)

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

Comments

2

You can do something like this, it will create array with new size based on provided.

    String[] temp = new String[] {"water", "shovel", "berries", "stick", "stone", "seed", "axe"};
    String[] val = Arrays.copyOf(temp, 20);

    System.out.println(val.length);
    System.out.println(Arrays.toString(val));

The output will be:

20
[water, shovel, berries, stick, stone, seed, axe, null, null, null, null, null, null, null, null, null, null, null, null, null]

2 Comments

Thanks! Although not ideal, it is closest to what I was trying to do.
@Rohan Great! Yeah... java has limitations((( You can try Kotlin which also work on JVM and can be used for android deveelopment. It's pretty nasty;)
1

It is not possible as such, but one can put null and assign later.

String[] arr = new String[] {"water", "shovel", "berries", "stick", null, null};

1 Comment

This seems like a good compromise of what the OP is trying to do, and the limitations of initializing an array. (Just a warning though the line you show won't compile.)
-2

Yes it is possible but little by difference.

String anArray = new String[] {"water", "shovel", "berries", "stick", "stone", "seed", "axe"};

create array of size 7

String anArray = new String[20];

create array of size 20 and than you can initilize it

anArray[0] = "water";
anArray[1] = "shovel";
...

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.