0

Is there a way in Java to assign multiple values to an Array in one statment then later you can still be able to append to the same array other values?

e.g. Having a String array defined already with length of 4

String[] kids = new String[4];

I would like to assign multiple values (2 values for example) to the array in one statment; maybe something close to the array init

kids = {"X", "Y"};

or the array redefinition

kids = new String[] {"X", "Y"};

but without loosing the initial array as later I will need to add to it other values e.g.

if(newKid) {
    kids[3] = "Z";
}

or there is no way to achieve this and have to assign values one by one

kids[0] = "X";
kids[1] = "Y";
if(newKid) {
    kids[3] = "Z";
}
4
  • If you want to keep the original array, use Arrays.copyOf(...) to copy it before modifying. Commented Jun 29, 2016 at 9:46
  • I was trying to avoid this as each time I need to append a new values to the array I will have to do a copy Commented Jun 29, 2016 at 9:49
  • You can't resize an array anyway. It's a fixed-size data structure. You have to copy the array if you want to append an element. Commented Jun 29, 2016 at 9:49
  • I don't need to resize it I know the size in advance as indicated e.g. new String[4]; and there are some values that I need to add it using one statement then later other data will be completed according to some conditions. Thanks Commented Jun 29, 2016 at 9:55

3 Answers 3

1

You will need to copy the array with the initialized values into a larger array:

String[] kids = Arrays.copyOf(new String[]{ "x", "y" }, 4);
kids[2] = "z";

Alternative copy solution:

String[] kids = new String[4];
System.arraycopy(new String[]{"x", "y"}, 0, kids, 0, 2);
kids[2] = "z";

Alternatively you could have empty Strings as placeholders:

String[] test ={ "x", "y", "", "" };
test[2] = "z";

Or you could use a List<String>:

List<String> kids = new ArrayList<>(4);
Collections.addAll(kids, "x", "y");
kids.add("z");

Alternative List<String> solution:

List<String> kids = new ArrayList<>(Arrays.asList("x", "y"));
kids.add("z");
1
  • List<String> kids = new ArrayList<>(Arrays.asList("x", "y")); kids.add("z"); this is exactly the solution I will do if I had to use List Commented Jun 29, 2016 at 10:08
0

It's solved here Resize an Array while keeping current elements in Java?

Btw, you can use Lists so you won't need to resize

0

You can do the following:

String[] kids = new String[4];
System.arraycopy(new String[] {"X", "Y"}, 0, kids, 0, 2);

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.