问题
My problem is that I need to copy a list but a deep copy. When I modify the list a
, I don't want to modify the list b
. I use JDK11 so I could use list.copyOf
but using that when I modify a
, b
is also modified. Am I doing something wrong?
b = List.copyOf(a);
System.out.println("A start:" + b.get(2).getSeating());
System.out.println("B start:" + b.get(2).getSeating());
a.get(2).setSeating(27);
System.out.println("Hi there" );
System.out.println("A end:" + a.get(2).getSeating());
System.out.println("B end:" + b.get(2).getSeating());
The output of that assignation:
回答1:
The copyOf method does not make a deep copy, according to the documentation it returns a non-mutable view, i.e. a read-only list. It does not make copies of the elements in the list. To make a deep copy you would basically need to iterate through the collection and deep-copy the elements one by one into a new collection. This can be tricky in the general case. Some objects support clone, others have custom copy methods, but in the general case Java has no deep copy methods that always works.
In short the solution differs depending on what you have in your list. As it seems to be custom objects from your application it is probably easiest to just iterate through the list and copy instances to a new list with a copy constructor or clone method that your provide in your class.
来源:https://stackoverflow.com/questions/54851349/java-how-can-i-use-correctly-list-copyof