avatar
immutable list# Java - 爪哇娇娃
p*p
1
I have writen some config data in a List and have to immutable reference,
how? or create a clone copy?
avatar
g*g
2
You can have your list as a field in another class,
say ImmutableList, and in this class you only expose
method that you want to expose. e.g. only the get(int i)
class ImmutableList {
private List data;
public Object get(int i) {
return data.get(i);
}
}

【在 p***p 的大作中提到】
: I have writen some config data in a List and have to immutable reference,
: how? or create a clone copy?

avatar
p*p
3
Well, I have to reture a List
object, so any suggestion?

【在 g*****g 的大作中提到】
: You can have your list as a field in another class,
: say ImmutableList, and in this class you only expose
: method that you want to expose. e.g. only the get(int i)
: class ImmutableList {
: private List data;
: public Object get(int i) {
: return data.get(i);
: }
: }

avatar
g*g
4
这个建议不加,因为是要只读的,一旦实现List,那些add/remove方法都要实现,
固然可以实现为空方法或抛异常,但都不如编译时就告诉你这个方法没有。
不过可以先定义一个ImmutableListInterface。

【在 p***p 的大作中提到】
: Well, I have to reture a List
: object, so any suggestion?

avatar
p*p
5
是不是还加个implements?
还是extends ArrayList,然后再overload
class ImmutableList implements List{
private List data;
public Object get(int i) {
return data.get(i);
}
}

【在 g*****g 的大作中提到】
: You can have your list as a field in another class,
: say ImmutableList, and in this class you only expose
: method that you want to expose. e.g. only the get(int i)
: class ImmutableList {
: private List data;
: public Object get(int i) {
: return data.get(i);
: }
: }

avatar
m*y
6
Collections.unmodifiableList(List list)

【在 p***p 的大作中提到】
: I have writen some config data in a List and have to immutable reference,
: how? or create a clone copy?

avatar
r*l
7
嘿嘿,这是用java的人给出的答案。前面的几个回答不错,但是因为java已经实现了,
就用不着费力气了。

【在 m******y 的大作中提到】
: Collections.unmodifiableList(List list)
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。