在Java中的getter和修改列表组合 [英] Combination of getter and list modification in Java

查看:166
本文介绍了在Java中的getter和修改列表组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我处理了一个Java问题,真正让我感到困惑。
我有以下的code:

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

当我一个元素添加到列表,吸气得到某种覆盖。这是因为 someList 就像在这种情况下,吸气结果的参考?还是什么别的原因导致这种效果?

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?

我用另一个列表解决了以下code中的问题:

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

但我还是某种困惑,因为我没有想到Java来表现这种方式。
谁能给我解释一下我做错了什么,为什么会这样?

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?

在此先感谢!

推荐答案

返回的结果确实只是一个相同的对象的引用作为您内部使用的副本。望着调用者不能修改的对象是容易出错。

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.

一个解决方案是一个参考返回一个不可修改的列表包装列表。参见 Col​​lections.unmodifiableList()。 getter方法​​调用者将无法修改列表。

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.

这篇关于在Java中的getter和修改列表组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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