如何在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;
    }
}

答案 1

初始化后,您可以执行beanList

beanList = Collections.unmodifiableList(beanList);

使其不可修改。(请参阅不可变集合与不可移动集合)

如果您既有应该能够修改列表的内部方法,又有不允许修改的公共方法,我建议您这样做

// public facing method where clients should not be able to modify list    
public List<Bean> getImmutableList(int size) {
    return Collections.unmodifiableList(getMutableList(size));
}

// private internal method (to be used from main in your case)
private List<Bean> getMutableList(int size) {
    List<Bean> beanList = new ArrayList<Bean>();
    int i = 0;

    while(i < size) {
        Bean bean = new Bean("name" + i, "address" + i, i + 18);
        beanList.add(bean);
        i++;
    }
    return beanList;
}

(您的对象似乎已经是不可变的。Bean


作为旁注:如果您碰巧使用Java 8 +,则可以表示如下:getMutableList

return IntStream.range(0,  size)
                .mapToObj(i -> new Bean("name" + i, "address" + i, i + 18))
                .collect(Collectors.toCollection(ArrayList::new));

答案 2

在 JDK 8 中:

List<String> stringList = Arrays.asList("a", "b", "c");
stringList = Collections.unmodifiableList(stringList);

在 JDK 9 中:

List stringList = List.of("a", "b", "c");

参考