p***p 发帖数: 559 | 1 I have writen some config data in a List and have to immutable reference,
how? or create a clone copy? |
g*****g 发帖数: 34805 | 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?
|
p***p 发帖数: 559 | 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); : } : }
|
g*****g 发帖数: 34805 | 4 这个建议不加,因为是要只读的,一旦实现List,那些add/remove方法都要实现,
固然可以实现为空方法或抛异常,但都不如编译时就告诉你这个方法没有。
不过可以先定义一个ImmutableListInterface。
【在 p***p 的大作中提到】 : Well, I have to reture a List : object, so any suggestion?
|
p***p 发帖数: 559 | 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); : } : }
|
m******y 发帖数: 102 | 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?
|
r*****l 发帖数: 2859 | 7 嘿嘿,这是用java的人给出的答案。前面的几个回答不错,但是因为java已经实现了,
就用不着费力气了。
【在 m******y 的大作中提到】 : Collections.unmodifiableList(List list)
|