Deep copying of an array of java objects

How can I use the mass of objects (native, non-native)?String, Integer and so on) copy it to another array along with copies of its fields? I use System.arraycopy I have no problem copying the second array, but the problem is that 2 different arrays refer to the same data (the same memory area), and when you change a variable in one array, it changes in the second one. How to avoid this? Example:

public class MyClass {
    public static void main(String args[]) {
        Mas mas1 = new Mas();
        mas1.num = 1;
        Mas mas2 = new Mas();
        mas2.num = 2;
        Mas mas3 = new Mas();
        mas3.num = 3;
        Mas[] massiv = new Mas[3];
        massiv[0] = mas1;
        massiv[1] = mas2;
        massiv[2] = mas3;
        System.out.println(massiv[0].num + " " + massiv[1].num + " " + massiv[2].num);

        Mas[] massiv2 = new Mas[3];

        System.arraycopy(massiv, 0, massiv2, 0, 3);

        System.out.println(massiv2[0].num + " " + massiv2[1].num + " " + massiv2[2].num);
        massiv2[0].num = 4;

        System.out.println(massiv[0].num + " " + massiv[1].num + " " + massiv[2].num);
        System.out.println(massiv2[0].num + " " + massiv2[1].num + " " + massiv2[2].num);
    }
}

class Mas {
    int num;
}

Conclusion:

1 2 3
1 2 3
4 2 3
4 2 3
Author: Илья, 2020-06-18

2 answers

You must copy each element of the array. You can't copy an array as a whole. You may have heard the term "Deep Copy".

You will need a for loop, no matter how ugly it is. And already in the loop, copy each object separately.

 0
Author: Sergei Buvaka, 2020-06-18 11:29:20

Native method System.arraycopy does not perform "Deep copying" of the array, as well as the method Arrays.copyOf. Elements from the old array are copied to the new array, i.e. references to objects. Deep copying of nested objects, including arrays, must be implemented independently, taking into account the necessary depth of copying, you can also use serialization.


Example of the "Deep copy" array algorithm. The new array is not copied to references to elements from the original array, and new objects are created:

static class Element {
    int num;

    public Element(int num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return String.valueOf(num);
    }
}
public static void main(String[] args) {
    Element[] arr = new Element[3];
    arr[0] = new Element(1);
    arr[1] = new Element(2);
    arr[2] = new Element(3);

    Element[] arr2 = new Element[3];

    IntStream.range(0, 3).forEach(i -> arr2[i] = new Element(arr[i].num));

    arr2[0].num = 4;

    System.out.println(Arrays.toString(arr));  // [1, 2, 3]
    System.out.println(Arrays.toString(arr2)); // [4, 2, 3]
}
 1
Author: , 2020-09-16 16:58:54