Add one more element to multi dimensional array in java

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

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

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(T[],%20int) https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(T[],%20int)

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

https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html


(*) 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);
}
// ...

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/39116515/add-one-more-element-to-multi-dimensional-array-in-java

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils