2008-10-14 29 views
6

Tengo dos matrices multidimensionales (bueno, en realidad son solo 2D) que tienen un tamaño inferido. ¿Cómo los cloné profundamente? Esto es lo que he conseguido hasta ahora:¿Clonación profunda de matrices multidimensionales en Java ...?

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

Una prueba para la igualdad original.equals(clone); escupe un falso. ¿Por qué? : |

Respuesta

3

El método equals() en matrices es el declarado en la clase Object. Esto significa que solo devolverá verdadero si el objeto es el mismo. Por lo mismo no significa lo mismo en CONTENIDO, sino lo mismo en MEMORIA. Por lo tanto, equals() en tus matrices nunca volverá verdadero ya que estás duplicando la estructura en la memoria.

1

Una prueba para la igualdad original.equals (clone); escupe un falso. ¿Por qué? : |

eso es porque está creando una nueva matriz con new Character[original.length][];.

Arrays.deepEquals(original,clone) debe devolver cierto.

-1

que consideran que esta respuesta para la clonación de matrices multidimensionales en 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(); 
+0

Esta técnica funciona para matrices multidimensionales. Simplemente use 'array' en lugar de' this' –

13
/**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; 
} 
+0

¡Gracias por esto! –

0

Igual solución @Barak (serializar y deserializar) con ejemplos (ya que algunas personas no podían entender y abajo votaron eso)

public static <T extends Serializable> T deepCopy(T obj) 
{ 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    try 
    { 
     ObjectOutputStream oos = new ObjectOutputStream(baos); 

     // Beware, this can throw java.io.NotSerializableException 
     // if any object inside obj is not Serializable 
     oos.writeObject(obj); 
     ObjectInputStream ois = new ObjectInputStream(
            new ByteArrayInputStream(baos.toByteArray())); 
     return (T) ois.readObject(); 
    } 
    catch ( ClassNotFoundException /* Not sure */ 
      | IOException /* Never happens as we are not writing to disc */ e) 
    { 
     throw new RuntimeException(e); // Your own custom exception 
    } 
} 

Uso:

int[][] intArr = { { 1 } }; 
    System.out.println(Arrays.deepToString(intArr)); // prints: [[1]] 
    int[][] intDc = deepCopy(intArr); 
    intDc[0][0] = 2; 
    System.out.println(Arrays.deepToString(intArr)); // prints: [[1]] 
    System.out.println(Arrays.deepToString(intDc)); // prints: [[2]] 
    int[][] intClone = intArr.clone(); 
    intClone[0][0] = 4; 

    // original array modified because builtin cloning is shallow 
    System.out.println(Arrays.deepToString(intArr)); // prints: [[4]] 
    System.out.println(Arrays.deepToString(intClone)); // prints: [[4]] 

    short[][][] shortArr = { { { 2 } } }; 
    System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]] 

    // deepCopy() works for any type of array of any dimension 
    short[][][] shortDc = deepCopy(shortArr); 
    shortDc[0][0][0] = 4; 
    System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]] 
    System.out.println(Arrays.deepToString(shortDc)); // prints: [[[4]]] 
Cuestiones relacionadas