List.of() vs List.copyOf()

Moderator: admin

Post Reply
2014098616
Posts: 5
Joined: Thu Oct 08, 2020 7:23 am
Contact:

List.of() vs List.copyOf()

Post 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

admin
Site Admin
Posts: 9122
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest