Java array assignment multiple values keeping the initial array -
is there way in java assign multiple values array in 1 statment later can still able append same array other values?
e.g. having string array defined length of 4
string[] kids = new string[4];
i assign multiple values (2 values example) array in 1 statment; maybe close array init
kids = {"x", "y"};
or array redefinition
kids = new string[] {"x", "y"};
but without loosing initial array later need add other values e.g.
if(newkid) { kids[3] = "z"; }
or there no way achieve , have assign values 1 one
kids[0] = "x"; kids[1] = "y"; if(newkid) { kids[3] = "z"; }
you need copy array initialized values 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 have empty strings placeholders:
string[] test ={ "x", "y", "", "" }; test[2] = "z";
or use 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");
Comments
Post a Comment