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";
}
Ali Abdel-Aziz
  • 275
  • 1
  • 4
  • 13
  • If you want to keep the original array, use [`Arrays.copyOf(...)`](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(T[],%20int)) to copy it before modifying. – Andy Turner Jun 29 '16 at 09: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 – Ali Abdel-Aziz Jun 29 '16 at 09: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. – Andy Turner Jun 29 '16 at 09: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 – Ali Abdel-Aziz Jun 29 '16 at 09:55

3 Answers3

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");
explv
  • 2,709
  • 10
  • 17
  • List kids = new ArrayList<>(Arrays.asList("x", "y")); kids.add("z"); this is exactly the solution I will do if I had to use List – Ali Abdel-Aziz Jun 29 '16 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

Community
  • 1
  • 1
Raskayu
  • 735
  • 7
  • 20
0

You can do the following:

String[] kids = new String[4];
System.arraycopy(new String[] {"X", "Y"}, 0, kids, 0, 2);
Michael Piefel
  • 18,660
  • 9
  • 81
  • 112