Stunner
Stunner

Reputation: 1121

Add one more element to multi dimensional array in java

A method is returning a 2-dimensional array in java. I want to add one more element to it. Not sure of the syntax of how to copy it to another new 2-d array& add one more element. Anyone have idea?

String arr[][]=getTwoDArray();

Now I want to add one more row to it. Something like this

String newArr[][] = new String[arr.length+1][];
arr[length+1][0]= {"car"};

Any idea?

Upvotes: 0

Views: 455

Answers (1)

Andy Turner
Andy Turner

Reputation: 140309

You can't resize arrays: their size is fixed at creation time.

You can only create a new array and copy the contents in; you can do this conveniently using Arrays.copyOf (*):

String newArr[][] = Arrays.copyOf(arr, arr.length + 1);
// Note that newArr[arr.length] is currently null.
newArr[arr.length] = new String[] { "car" };

However, as pointed out by @KevinEsche in his comment on the question, you might find an ArrayList (or maybe some other kind of List) more convenient to use: although this is also backed by an array, and needs to resize that array occasionally, it hides the details from you.


(*) The gotcha here is that Arrays.copyOf performs a shallow copy of arr, so any changes to the elements of arr[i] will be reflected in the elements of newArr[i] (for 0 <= i < arr.length). Should you need it, you can make a deep copy by looping over the elements of arr, calling Arrays.copyOf on each.

String newArr[][] = Arrays.copyOf(arr, arr.length + 1);
for (int i = 0; i < arr.length; ++i) {
  newArr[i] = Arrays.copyOf(arr[i], arr[i].length);
}
// ...

Upvotes: 5

Related Questions