0

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?

2
  • 6
    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. Commented Aug 24, 2016 at 7:05
  • 2
    That´s what a Collection, in this case a List, would be there for Commented Aug 24, 2016 at 7:08

1 Answer 1

5

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);
}
// ...
Sign up to request clarification or add additional context in comments.

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.