Why can we change the unmodifiable list if we have the original one?

前端 未结 7 723
时光取名叫无心
时光取名叫无心 2020-12-10 15:56

By looking at the code of Collections class, i got to know that when we are using the method unmodifiableList(List list) or unmodifiableCollection(Coll

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 16:11

    I Found one way to do this is

    List unmodifiableList = Collections.unmodifiableList( new ArrayList(modifiableList));
    
    List strings = new ArrayList();
            // unmodifiable.add("New string");
            strings.add("Aha 1");
            strings.add("Aha 2");
            List unmodifiable = Collections.unmodifiableList(strings);
            List immutableList = Collections.unmodifiableList(new ArrayList<>(strings));
            // Need some way to fix it so that Strings does not Modify
            strings.add("Aha 3");
            strings.add("Aha 4");
    
            strings.remove(0);
    
            for (String str : unmodifiable) {
                System.out.println("Reference Modified :::" + str);
            }
    
            for (String str : immutableList) {
                System.out.println("Reference Modified :::" + str);
            }
    

提交回复
热议问题