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

Roh*_*kar 1 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)
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 6

来自Javadoc:

返回指定列表的不可修改视图.

您已在原始列表中创建了一个视图 - 对原始列表的更改将通过视图反映出来.

  • @RohitKolhekar你在数据结构意义上误解了"视图"的概念. (3认同)