What is the difference between List.of
and Arrays.asList
in Java?
Java 9 introduced new factory methods for lists using List.of
, like this:
List<String> strings = List.of("first", "second");
How does this differ from the traditional approach using Arrays.asList
, such as:
Arrays.asList(1, 2, 3);
What are the key distinctions in terms of immutability, performance, and behavior when using java list.of
compared to Arrays.asList
?
From my experience, one of the key distinctions lies in immutability. When you use java list.of
, it creates an immutable list, which means that once it’s created, you can’t modify the contents—no adding, removing, or updating the elements. If you try to modify the list, you’ll get an UnsupportedOperationException
. For example:
List<Integer> list1 = List.of(1, 2, 3); // Immutable
list1.add(4); // Throws UnsupportedOperationException
In contrast, Arrays.asList
returns a fixed-size list. You can modify the elements, but you can’t add or remove any items. For instance:
List<Integer> list2 = Arrays.asList(1, 2, 3); // Fixed size
list2.set(0, 99); // Works fine
list2.add(4); // Throws UnsupportedOperationException
So, if you need a list that should never be modified, java list.of is definitely the better choice.
Absolutely, Macy! And another important difference I’ve noticed is how null values are handled. java list.of
throws a NullPointerException
if you try to include null
as an element. For example:
List<String> list1 = List.of(null); // Throws NullPointerException
But with Arrays.asList
, you can include null
values without any issues:
List<String> list2 = Arrays.asList(null); // Works fine
If your list might contain null
values, Arrays.asList could be the safer choice here, but if you want to avoid any potential issues, java list.of’s strict immutability is great for catching bugs early.
Exactly, Jacqueline! Also, java list.of is designed to be more memory-efficient. Since it creates an immutable list, it eliminates some of the overhead involved in the mutable fixed-size list that Arrays.asList
creates. This can lead to better performance, especially when dealing with large datasets.
For example, when you need a lightweight, optimized list for performance, java list.of is the way to go. It’s more efficient because it skips the unnecessary overhead of the ArrayList
that Arrays.asList
uses under the hood.
List<Integer> fastList = List.of(1, 2, 3, 4, 5); // More efficient
List<Integer> arrayList = Arrays.asList(1, 2, 3, 4, 5); // More overhead
So, if you’re concerned about performance and need immutability, java list.of will serve you much better.