Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy a two dimensional array of strings?

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?

like image 841
Lily Avatar asked Dec 13 '22 04:12

Lily


2 Answers

I'm not sure what the n parameter is for, but if I needed such a function, I'd use something like this:

public static String[][] copy(String[][] matrix) {
  String[][] copy = new String[matrix.length];
  for (int idx = 0; idx < matrix.length; ++idx)
    copy[idx] = matrix[idx].clone();
  return copy;
}

You don't need to create a copy of the String, because they are immutable. As pointed out by Michael in the comments, the String(String) constructor might be useful if the original string was created as a substring of some very large string. Another use is when you are using String objects as locks (not recommended), and want a private instance to avoid deadlocks.

Also, your check to see whether an element is null before assigning is unnecessary; if you have your loops setup correctly, the element is guaranteed to be null. (And if it's not, what's the harm in overwriting it?)

like image 188
erickson Avatar answered Dec 29 '22 04:12

erickson


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.

like image 24
Michael Borgwardt Avatar answered Dec 29 '22 05:12

Michael Borgwardt