javacollections

List.of and List.copyOf methods


I understand that List.of and List.copyOf create immutable clone lists of the original list, so in my understanding, the below code should print [1], [1, 2] when it prints [[1, 2]], [1, 2]? How does List.of take the most recent view of the initial collection, col?

Collection<Number> col = new HashSet<>();
col.add(1);
var list1 = List.of(col); //1
col.add(2); //2
var list2 = List.copyOf(col); //3
System.out.println(list1+", "+list2);

Solution

  • List.of creates a new list with the parameters as elements. List.copyOf creates a new list with the same elements as the single Collection argument.

    Pseudocode Examples (note the square brackets):

    List.of(1,2,3) == [1,2,3]
    List.copyOf([1,2,3]) == [1,2,3]
    List.of([1,2,3]) == [[1,2,3]]
    List.of([1,2,3], [4,5,6]) == [[1,2,3], [4,5,6]]
    

    The third line is similar to what's happening in your code. of creates a list that has the parameters as elements. What parameters did you give it? One modifiable set. So it creates an unmodifiable list with a single element, that element being your modifiable set. Note also that of does not copy the set.

    copyOf creates an unmodifiable list with the same elements as the collection that you passed in. You passed in col, which has the elements 1, 2, so it creates an unmodifiable List with the elements 1, 2.