gpt4 book ai didi

java - 馆藏副本

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:43 26 4
gpt4 key购买 nike

你通常如何在 Java 中进行集合 getter?例如,我有两个类(class)。

public class A
{
String s = "1";
A () {}
}

public class B
{
List<A> list;
public B()
{
list = new ArrayList<>();
}
public List<A> getList()
{
return list;
}

}

如果我有这样的 getter,我可以这样做:

B elem = new B();
elem.getList().add(new A());

所以它打破了 getter 的想法。

我可以

 public List<A> getList()
{
return new ArrayList<>(list);
}

但是,如果我修改结果的某些元素,原始元素将被更改。

最佳答案

Collection.unmodifiableList(list) 返回一个不可修改的集合:

public List<A> getList() {
return Collections.unmodifiableList(list);
}

引用 Javadoc:

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.

因此无法向返回的列表添加/删除元素,也无法修改其元素。

如果您想返回列表的深层克隆而不是不可修改的列表,请参阅 this question .

关于java - 馆藏副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33889228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com