How to create Immutable List in java?

后端 未结 7 1867
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 01:16

I need to convert mutable list object to immutable list. What is the possible way in java?

public void action() {
    List mutableList =          


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 02:13

    Below solution is for making list as Immutable without using any API.

    Immutable Object with ArrayList member variable

    public final class Demo {
    
        private final List list = new ArrayList();
    
        public Demo() {
            list.add("A");
            list.add("B");
        }
    
        public List getImmutableList() {
            List finalList = new ArrayList();
            list.forEach(s -> finalList.add(s));
            return finalList;
        }
    
        public static void main(String[] args) {
            Demo obj = new Demo();
            System.out.println(obj.getImmutableList());
            obj.getImmutableList().add("C");
            System.out.println(obj.getImmutableList());
        }
    }
    

    So the actual list will not change, always output will be [A,B]

提交回复
热议问题