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/