java - 如果我们在父列表中添加元素,为什么 JDK 会向 UnmodifyableList 添加一个元素

标签 java collections

 List<Person> intList = new ArrayList<Person>();
        // creating Parent List
        // Person Class contains two fields Name and Age
        Person p1 = new Person("James", 28);
        Person p2 = new Person("Duncan", 26);
        Person p3 = new Person("Lukan",32);
        Person p4 = new Person("Therry", 12);
        // Creating ParentList
        intList.add(p1);
        intList.add(p2);        
        intList.add(p3);
        intList.add(p4);

        ImmutableList<Person> immutableList = ImmutableList.copyOf(intList);        
        List<Person> unModifybale = Collections.unmodifiableList(intList);
        //Adding element to parentList
        intList.add(p4);        

        System.out.println("\n" +intList);  

        // Here unModifyble List also gets element after added in parent list
        // why does it happen like this?

        System.out.println("\n unModifyble"+ unModifybale);

        System.out.println("\n Immutable" + immutableList)

最佳答案

来自 the Javadoc :

Returns an unmodifiable view of the specified list.

您已经在原始列表中创建了一个 View - 对原始列表的更改将通过该 View 反射(reflect)出来。

关于java - 如果我们在父列表中添加元素,为什么 JDK 会向 UnmodifyableList 添加一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34458739/

相关文章:

java - 如何调用以 Object... 作为参数的方法

java - Java中的arrayList是数组还是列表?

java - 将 HashMap 键迭代器转换为列表迭代器

java - 在我通过电子邮件发送给自己后,android 中文件上的 md5 校验和与 md5 不匹配

java - ForkjoinPool 没有 BlockingQueue

java - Boolean/boolean 如何作为 Java 中 HashMap 的键?

python - 从 OrderedDict 和 defaultdict 继承

java - 对于 contains 我们是否应该覆盖 java 中 hashset 的 hashcode 和 equals

java - Stream.of(item).collect(Collectors.toSomeCollection()) 比 new SomeCollection(Arrays.asList(item)) 快吗?

Java Lambda 复用 Stream