如何在Java中创建不可变列表? [英] How to create Immutable List in java?

查看:71
本文介绍了如何在Java中创建不可变列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将可变列表对象转换为不可变列表。 Java中可能的方法是什么?

I need to convert mutable list object to immutable list. What is the possible way in 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



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;
    }
}


推荐答案

一次您的 beanList 已被初始化,您可以

Once your beanList has been initialized, you can do

beanList = Collections.unmodifiableList(beanList);

使其无法修改。 (请参见不变和不可修改的收藏

to make it unmodifiable. (See Immutable vs Unmodifiable collection)

应该可以修改列表的内部方法,以及不允许修改的公共方法,建议您这样做

If you have both internal methods that should be able to modify the list, and public methods that should not allow modification, I'd suggest you do

// 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 对象似乎已经是不可变的。)

(Your Bean objects already seem immutable.)

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

As a side-note: If you happen to be using Java 8+, your getMutableList can be expressed as follows:

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

这篇关于如何在Java中创建不可变列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆