About Question enthuware.ocpjp.v11.2.3407 :
Posted: Tue Apr 23, 2024 7:38 pm
In the explanation part, what is the meaning of this part:
"While the collection cannot be modified via the unmodifiable view, the underlying collection may still be modified via a direct reference to it. However, the collections returned by the of/ofEntries API methods are in fact unmodifiable."
The text states that methods unmodifiableXXX() creates unmodifiable views, but the underlying collection may still be modified, whereas this is not the case with of/ofEntries. But I tried the code below, using of(), and changed the original arraylist. It did modified the reference from List.of(). So, what is the meaning of "API methods are in fact unmodifiable"?
public static void main(String[] args) {
Collection<Number> col = new HashSet<>();
col.add(1);
var list1 = List.of(col);
col.add(2);
System.out.println(list1); //[[1, 2]]
System.out.println(col == list1.get(0)); //returns true, showing it points to the same object
}
"While the collection cannot be modified via the unmodifiable view, the underlying collection may still be modified via a direct reference to it. However, the collections returned by the of/ofEntries API methods are in fact unmodifiable."
The text states that methods unmodifiableXXX() creates unmodifiable views, but the underlying collection may still be modified, whereas this is not the case with of/ofEntries. But I tried the code below, using of(), and changed the original arraylist. It did modified the reference from List.of(). So, what is the meaning of "API methods are in fact unmodifiable"?
public static void main(String[] args) {
Collection<Number> col = new HashSet<>();
col.add(1);
var list1 = List.of(col);
col.add(2);
System.out.println(list1); //[[1, 2]]
System.out.println(col == list1.get(0)); //returns true, showing it points to the same object
}