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

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

问题描述

今天我处理了一个让我很困惑的 Java 问题.我有以下代码:

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

当我向列表中添加一个元素时,getter 会被某种覆盖.这是因为 someList 在这种情况下就像对 getter 结果的引用一样吗?或者还有什么原因导致这种效果?

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

但我仍然有些困惑,因为我没想到 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.

一种解决方案是返回对包含列表的不可修改列表的引用.参见 Collections.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和list修改的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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