How to create Immutable List in java?

后端 未结 7 1764
隐瞒了意图╮
隐瞒了意图╮ 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<String> list = new ArrayList<String>();
    
        public Demo() {
            list.add("A");
            list.add("B");
        }
    
        public List<String> getImmutableList() {
            List<String> finalList = new ArrayList<String>();
            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]

    0 讨论(0)
提交回复
热议问题