Domanda

I've been stumped on this for a few days now so after a lot of research and coffee have come to the conclusion that I need to do a 'deep copy'. Apparently in Java, you can't copy an object as you're just copying the reference to the object so you always end up modifying the object itself.

What is the best way to extract an Integer array of times from an object (it's an Android timer app) and then keep those times somewhere so the user can 'reset' the times at any point, re-populating a list with the default times.

It may be better to take the copy from the object and use those instead of modifying the object, and then use the object to re-grab the default times when needed?

È stato utile?

Soluzione

Try this one:

public static void main(String[] args) {
    List<Integer> times = new ArrayList<Integer>();
    times.add(1);
    times.add(2);
    times.add(3);

    List<Integer> timesCopy = new ArrayList<Integer>(times);
    timesCopy.remove(0);

    System.out.println(times);
    System.out.println(timesCopy);
}

timesCopy has been modified but times is still as in the beggining.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top