List.of() vs List.copyOf()
Posted: Thu Oct 08, 2020 7:36 am
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
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