Combination of getter and list modification in Java

对着背影说爱祢 提交于 2020-01-05 07:25:42

问题


today i dealt with a Java problem that really confused me. I have the following code:

List<ObjectXY> someList = obj.getListOfObjectsXY(); // getter returns 2 elements
someList.add(new ObjectXY());

obj.getListOfObjectsXY(); // getter now returns 3 elements

When i add an element to a list, the getter gets some kind of overwritten. Is this because someList acts like a reference on the result of the getter in this case? Or what else causes this effect?

I solved the problem with the following code by using another list:

List<ObjectXY> someList = obj.getListOfObjectsXY(); // result: 2 elements

List<ObjectXY> someOtherList = new ArrayList<ObjectXY>();
someOtherList.addAll(someList);
someOtherList.add(new ObjectXY());

obj.getListOfObjectsXY(); // result: 2 elements

But i am still some kind of confused because i didn't expect Java to behave this way. Can anyone explain to me what i did wrong and why it is so?

Thanks in advance!


回答1:


The returned result is indeed just a copy of a reference to the same object as you are using internally. Counting on the caller to not modify the object is error-prone.

One solution is to return a reference to an unmodifiable list wrapping your list. See Collections.unmodifiableList(). The getter caller will be unable to modify your list.




回答2:


Is this because someList acts like a reference on the result of the getter in this case?

Yes. The list you received was just a reference to the same, original list you had. Any changes made on this variable would be reflected on the original list.

By adding the list's values to a new list you explicitly constructed a new object and thus they are separated.




回答3:


In your case, obj.getListOfObjectsXY() everytime return you the same object and in Java object references are pass-by-value. So, when you do a someList.add(new ObjectXY());, it's actually setting the property of the object someList which is poiting to obj.getListOfObjectsXY().

And in the latter case, you are just copying someList to someOtherList. Then you added one more element to the same someOtherList but not to the someList. So, you getting 2 elements in obj.getListOfObjectsXY(); is perfectly valid.



来源:https://stackoverflow.com/questions/18290370/combination-of-getter-and-list-modification-in-java

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