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.
我已经被这几天困住了,所以经过大量的研究和咖啡得出结论我需要做一个“深层复制”。显然在Java中,您不能复制对象,因为您只是复制对象的引用,因此您总是最终修改对象本身。
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.
从对象(它是Android计时器应用程序)中提取Integer数组的最佳方法是什么,然后将这些时间保留在某处,以便用户可以在任何时候“重置”时间,使用默认时间重新填充列表。
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
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.
timesCopy已被修改,但时间仍然与开始时一样。
#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.
timesCopy已被修改,但时间仍然与开始时一样。