Java-How can i use correctly list.copyOf? [duplicate]

北城余情 提交于 2021-01-29 02:37:18

问题


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:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!