Java-如何正确使用list.copyOf? [英] Java-How can i use correctly list.copyOf?

查看:169
本文介绍了Java-如何正确使用list.copyOf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我需要复制列表,但需要复制深层副本.当我修改列表 a 时,我不想修改列表 b .我使用JDK11,因此可以使用 list.copyOf ,但在修改 a 时也会使用它,同时也修改了 b .我在做错什么吗?

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 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.

这篇关于Java-如何正确使用list.copyOf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆