Page 1 of 1

List.of() vs List.copyOf()

Posted: Thu Oct 08, 2020 7:36 am
by 2014098616
Hello Admin, I have been trying to understand the difference between the two static methods List.of()[Java9] vs List.copyOf()[Java10]. I don't seem to find any difference. I am running Java 11.

These are my observations:

List.of()
1. List<Integer> numbers = List.of(1,2,3); this code is okay, however List<Integer> numbers = List.of(1,2,3, null); results in nullpointerexception
2. List<Integer> numbers = List.of(1,2,3); numbers.add(4); this results in unsupportedoperationexception
3. List<Integer> numbers = List.of() generates an empty list

List.of()
1. List<Integer> numbers = List.copyOf(List.of(1,2,3)); this code is okay, however List<Integer> numbers = List.of(1,2,3, null); results in nullpointerexception
2. List<Integer> numbers = List.copyOf(List.of(1,2,3)); numbers.add(4); this results in unsupportedoperationexception
3. List<Integer> numbers = List.copyOf(List.of()) generates an empty list

Re: List.of() vs List.copyOf()

Posted: Fri Oct 09, 2020 8:53 am
by admin
Well, the difference is that List.copyOf takes a Collection as an argument and creates a new unmodiable list containing all the elements of the original collection, while List.of takes multiple individual elements as arguments!
Both return an unmodifiable list, so, in that respect they are same.