How to copy 2d String array?
15,979
Solution 1
Java has a built in function called arraycopy that can do this for you without a double for loop. Much more efficient.
Solution 2
First of all the newer array has more elements that source array so decide what you want to do about it. Also if old array is called array call the new array by a different name say newarray.
for ( int i = 0; i < 3; ++i )
{
for( int j = 0; j < 2; ++i )
{
newarray[i][j] = array[i][j];
}
}
Author by
Carlo
IT Business Analyst whose sole purpose is to make a better life of Myself #ups I meant a better performance of a system
Updated on June 13, 2022Comments
-
Carlo almost 2 years
I'm having difficulty copying string array values into a new string array.
For example:
String[][] array = new String[3][2]; array[0][0] = "hello"; array[0][1] = "1"; array[1][0] = "guys"; array[1][1] = "2"; array[2][0] = "good "; array[2][1] = "3"; array = new String [5][2]; all the value in the first array to be copied array[3][0] = ""; array........;
I tried this method but it keeps me giving null pointer issues whenever I want to insert a new value.
String[][] array = new String[3][2]; array[0][0] = "olo"; array[0][1] = "ada "; array[1][0] = "apa"; array[1][1] = "dengan"; array[2][0] = "si "; array[2][1] = "carlo"; String[][] newArray = new String[5][2]; newArray = Arrays.copyOf(array, 5); array = new String[5][2]; array = Arrays.copyOf(newArray, 5); array[3][0] = "lo"; array[3][1] = "gw"; array[4][0] = "end"; array[4][1] = "ennnnnd"; for (int r = 0; r < array.length; r++) { for (int c = 0; c < array[r].length; c++) { System.out.print(" " + array[r][c]); } System.out.println(""); }
How can I copy this 2d string array?
-
Carlo over 12 yearswhat if I want that both array having the same name is there any ways to do so ? thanks
-
parapura rajkumar over 12 yearsyou can copy it into a newarray. and then do
array=newarray
. To copy you need to ability to refer to both source and destination , if they are both called the same it might kinda get tricy -
Amir Raminfar over 12 yearsYou still have to call arraycopy for the second dimension items. right?
-
Carlo over 12 yearsbtw how to call the second dimmension for copying