1
votes

My question is how to make a deep copy in java. Right now this is my code but I don't think this is correct.

@Override
public ListInterface<E> copy() {
    ListerInterface<E> temp = new List<E>();

    if (isEmpty()) {
        return null;
    } else {
        goToFirst();

        do {
            temp.inset(retrieve());
        } while (currentNode.next != null);

        currentNode = currentNode.next;
    }

    return temp;
}

So does anybody know what I should change in my code to get a deep copy that is correct?

2
Please add a Minimal, Complete, and Verifiable example. Since it is your first question on SO, you might read the guide on asking good questions. - M. le Rutte
About the objects in references: do you need them to get cloned? - gthanop
Maybee consult Arrays.deepEquals(...) method? - gthanop

2 Answers

0
votes

The code below copies a list which may contain other lists as referenced objects:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(final String[] args) {
        final ArrayList list = new ArrayList();
        list.add(Arrays.asList("A", "B", "C"));
        list.add("D");
        System.out.println(list);
        final ArrayList out = new ArrayList();
        deepCopy(out, list);
        System.out.println(out);
    }

    public static void deepCopy(final List out,
                                final List in) {
        for (Object o: in)
            if (o instanceof List) {
                final ArrayList copy = new ArrayList();
                deepCopy(copy, (List)o);
                out.add(copy);
            }
            else
                out.add(o);
    }
}

Edit:
If you want the referenced objects to be cloned, you have to have access to the clone method of the referenced objects.

0
votes

Just use MicroStream Object Copier.

    ObjectCopier objectCopier = ObjectCopier.New();

    Customer customer = root.getCustomer(id);

    Customer customerCopy = objectCopier.copy(customer);

This utility provides the full deep copy of any object graph in Java. Be careful of the cyclic references. You can easily make o copy of your whole memory graph.

https://docs.microstream.one/manual/storage/storing-data/deep-copy.html