如何在java中创建不可变列表?
2022-08-31 16:54:34
我需要将可变列表对象转换为不可变列表。Java中可能的方法是什么?
public void action() {
List<MutableClass> mutableList = Arrays.asList(new MutableClass("san", "UK", 21), new MutableClass("peter", "US", 34));
List<MutableClass> immutableList = immutateList(mutableList);
}
public List<MutableClass> immutateList(List<MutableClass> mutableList){
//some code here to make this beanList immutable
//ie. objects and size of beanList should not be change.
//ie. we cant add new object here.
//ie. we cant remove or change existing one.
}
MutableClass
final class MutableClass {
final String name;
final String address;
final int age;
MutableClass(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
}