Java 中非原始变量之间按值赋值
private List<CourseGroupBean> courseGroups = new ArrayList<CourseGroupBean>();
...
courseGroups = getAlgorithmUtil().listCourses();
...
List<CourseGroupBean> courseGroupsTwo = courseGroups;
我知道,如果我执行第三行,它将把 courseGroups 的引用分配给 courseGroupsTwo,但我只想分配它的值。在 Java 中如何做到这一点?
编辑
我的意思是,当我在 courseGroupsTwo 中删除/添加对象时,它不能更改 courseGroups 中的任何内容。
private List<CourseGroupBean> courseGroups = new ArrayList<CourseGroupBean>();
...
courseGroups = getAlgorithmUtil().listCourses();
...
List<CourseGroupBean> courseGroupsTwo = courseGroups;
I know that if I do the third line it will assing the reference of courseGroups to courseGroupsTwo but I want to assign just the values of it. How to do that in Java?
EDIT
I mean, when I remove/add an object at courseGroupsTwo it musn't change anything at courseGroups.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java 本身不支持对象的按值复制,因此您必须自己执行此操作:
将执行
courseGroups
的浅表复制,即它将创建一个包含与以下内容相同的对象的新列表:课程组
。如果需要,您可以将ArrayList
替换为更合适的List
实现。如果您愿意,还可以使用
克隆
。clone
有点令人讨厌,因为您需要在克隆之后进行强制转换。强制转换通常很糟糕,因为它可能会引入运行时错误,而如果出现问题,上面的代码将生成编译时错误。Java doesn't natively support copy-by-value for Objects, so you have to do it yourself:
will perform a shallow copy of
courseGroups
, i.e. it will create a new list that contains the same objects ascourseGroups
. You can replaceArrayList
with a more appropriateList
implementation if required.You can also use
clone
if you like.clone
is a bit nasty because you need to do a cast after the clone. Casting is generally bad because it possibly introduces run-time errors, whereas the code above will generate compile-time errors if something is wrong.您需要对列表进行“深层复制”。请参阅此 StackOverflow 答案。
You need to do a 'deep copy' of the list. See this StackOverflow answer.
但不仅仅是调用 .clone()。根据下面的资源,您的类还必须实现 Cloneable 接口;否则,将抛出 CloneNotSupportedException:
http: //www.roseindia.net/java/example/java/util/clone-method-example-in-java.shtml
But there is more than just calling .clone(). According to this resource below, your class also must implement the interface Cloneable; otherwise, a CloneNotSupportedException is thrown:
http://www.roseindia.net/java/example/java/util/clone-method-example-in-java.shtml
调用构造函数
ArrayList(Collection)
:Call constructor
ArrayList(Collection<? extends E>)
: