views:

2699

answers:

6

I have two multidimensional arrays (well actually they're only 2D) which have inferred size. How do I deep clone them? Here's what I have gotten so far:

public foo(Character[][] original){
 clone = new Character[original.length][];
 for(int i = 0; i < original.length; i++)
    clone[i] = (Character[]) original[i].clone();
}

A test for equality original.equals(clone); spits out a false. Why? :|

+3  A: 

You might want to check out the java.util.Arrays.deepEquals and java.util.Arrays.equals methods.

I'm afraid the equals method for array objects performs a shallow comparison, and does not properly (at least for this case) compare the inner Character arrays.

abahgat
+2  A: 

equals() method on arrays is the one declared in Object class. This means that it will only returns true if the object are the same. By the same it means not the same in CONTENT, but the same in MEMORY. Thus equals() on your arrays will never return true as you're duplicating the structure in memory.

gizmo
+1  A: 

A test for equality original.equals(clone); spits out a false. Why? :|

thats because you are creating a new array with new Character[original.length][];.

Arrays.deepEquals(original,clone) should return true.

Andreas Petersson
A: 

I found this answer for cloning multidimensional arrays on jGuru:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object deepCopy = ois.readObject();
Barak Schiller
+1  A: 

Thanks for all the answers. The deepEquals() method worked! :D Now how do I access each element of that array of inferred size? ( Sorry for the dumb question. :| ) Regular System.out.print(original[0][0]); doesn't work.

+1  A: 
/**Creates an independent copy(clone) of the boolean array.
 * @param array The array to be cloned.
 * @return An independent 'deep' structure clone of the array.
 */
public static boolean[][] clone2DArray(boolean[][] array) {
    int rows=array.length ;
    //int rowIs=array[0].length ;

    //clone the 'shallow' structure of array
    boolean[][] newArray =(boolean[][]) array.clone();
    //clone the 'deep' structure of array
    for(int row=0;row<rows;row++){
        newArray[row]=(boolean[]) array[row].clone();
    }

    return newArray;
}