0

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?

1
  • 1
    You can .clone() an array; if the elements of the array implement Cloneable you'll have a pristine copy. Note that it also works with most List implementations
    – fge
    Mar 29, 2014 at 18:30

1 Answer 1

1

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.

3
  • 1
    Yep, since Integer is immutable, this works; doesn't work quite well if elements are not immutable though ;)
    – fge
    Mar 29, 2014 at 18:37
  • Thanks for the answer, it was very helpful! But, can I ask why you do timesCopy.remove(0)? On my setup it removed the first index from the list (as I expected) which meant I was one short!
    – Mint_Sauce
    Apr 3, 2014 at 20:53
  • Aaah, fair enough! Thanks again. :)
    – Mint_Sauce
    Apr 3, 2014 at 22:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.