Logo

dev-resources.site

for different kinds of informations.

List.of() vs Arrays.asList() in java

Published at
1/5/2025
Categories
Author
realNameHidden
Categories
1 categories in total
open
List.of() vs Arrays.asList() in java


When working with Java, both List.of() (introduced in Java 9) and Arrays.asList() (available since Java 1.2) are commonly used to create lists, but they have subtle differences that can cause unexpected behavior and even crash your code if not understood properly. Let's explore these differences:

1. Mutability
List.of():
The list returned by List.of() is immutable, meaning you cannot modify it after creation. Any attempt to add, remove, or modify elements will throw an UnsupportedOperationException.
Example

List<String> list = List.of("apple", "banana", "orange");
list.add("grape"); // Throws UnsupportedOperationException

Arrays.asList():
The list returned by Arrays.asList() is mutable but with limitations. You can modify elements in the list, but you cannot change the size (i.e., add or remove elements). This is because Arrays.asList() returns a fixed-size list backed by the array.
Example:

List<String> list = Arrays.asList("apple", "banana", "orange");
list.set(1, "grape"); // Works fine (modifying the element)
list.add("grape"); // Throws UnsupportedOperationException (size cannot change)

2. Null Handling
List.of():
List.of() does not allow null values. If you try to create a list with null elements, it will throw a NullPointerException.
Example:

List<String> list = List.of("apple", null, "orange"); // Throws NullPointerException

Arrays.asList():
Arrays.asList() allows null values and handles them just like any other element.

Example:

List<String> list = Arrays.asList("apple", null, "orange"); // No issues with null values

3. Thread Safety
List.of():
Being immutable, the list returned by List.of() is inherently thread-safe since no modifications can occur.
Arrays.asList():
Arrays.asList() is not thread-safe because it's backed by an array, which can be modified in multiple threads without synchronization.

Featured ones: