I’m working with a program that uses two-dimensional arrays of Strings (probably not that smart to begin with, but eh), and I’d like to write a function that takes one of these arrays (let’s say array1), makes an independent copy, and returns it (let’s say array2). However, when I then change a value in array2, it seems to be reflected in array1.
My function currently looks something like this:
public static String[][] copy(String[][] matrix, int n) { String[][] out = new String[n+1][n+1]; for (int i = 0; i < n+1; i++) for (int j = 0; j < n+1; j++) { if(matrix[i][j] != null) { String cp = new String(matrix[i][j]); out[i][j] = cp; } } return out; }
I declare a new array of Strings, and then iterate through it, copying each value individually. When that didn’t work, I even tried explicitly declaring a new string from each old string and putting that in the array instead.
Can anyone tell me where I’m going wrong?
Your method looks like it should work, though passing in n as a parameter makes it brittle, using the input array’s length field would be better, and you could even handle jagged arrays that way.
Making a copy of the contents is not necessary, since Strings cannot be changed – which leads to the main question: What kind of changes are you making that seem to be reflected in the copy? Show us the code that does this.