Add one more element to multi dimensional array in java -


a method returning 2-dimensional array in java. want add 1 more element it. not sure of syntax of how copy new 2-d array& add 1 more element. have idea?

string arr[][]=gettwodarray(); 

now want add 1 more row it. this

string newarr[][] = new string[arr.length+1][]; arr[length+1][0]= {"car"}; 

any idea?

you can't resize arrays: size fixed @ creation time.

you can create new array , copy contents in; can conveniently using arrays.copyof (*):

string newarr[][] = arrays.copyof(arr, arr.length + 1); // note newarr[arr.length] null. newarr[arr.length] = new string[] { "car" }; 

however, pointed out @kevinesche in comment on question, might find arraylist (or maybe other kind of list) more convenient use: although backed array, , needs resize array occasionally, hides details you.


(*) gotcha here arrays.copyof performs shallow copy of arr, changes elements of arr[i] reflected in elements of newarr[i] (for 0 <= < arr.length). should need it, can make deep copy looping on elements of arr, calling arrays.copyof on each.

string newarr[][] = arrays.copyof(arr, arr.length + 1); (int = 0; < arr.length; ++i) {   newarr[i] = arrays.copyof(arr[i], arr[i].length); } // ... 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -