开发者

Assignment between non-primitive variables by value in Java

开发者 https://www.devze.com 2023-02-02 08:12 出处:网络
private List<CourseGroupBean> courseGroups = new ArrayList<CourseGroupBean&开发者_Python百科gt;();
private List<CourseGroupBean> courseGroups = new ArrayList<CourseGroupBean&开发者_Python百科gt;();
...
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.


Java doesn't natively support copy-by-value for Objects, so you have to do it yourself:

List<CourseGroupBean> courseGroupsTwo = new ArrayList<CourseGroupBean>(courseGroups);

will perform a shallow copy of courseGroups, i.e. it will create a new list that contains the same objects as courseGroups. You can replace ArrayList with a more appropriate List 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.


You need to do a 'deep copy' of the list. See this StackOverflow answer.


     List<CourseGroupBean> courseGroupsTwo = (ArrayList<CourseGroupsBean>) courseGroups.clone();

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


Call constructor ArrayList(Collection<? extends E>):

List<CourseGroupBean> courseGroupsTwo = new ArrayList<CourseGroupBean>(courseGroups)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号