Here’s a clear comparison of List.of()
and Arrays.asList()
in Java:
1. Mutability
- List.of() (Java 9+): Returns an immutable list. No adding, removing, or replacing elements. Any mutating operation (like
add()
,remove()
, orset()
) throwsUnsupportedOperationException
. - Arrays.asList() (Java 1.2+): Returns a fixed-size list backed by the provided array. You cannot add or remove elements, but you can change elements with
set()
.
2. Null Handling
- List.of(): Does not allow null elements. Passing a
null
will throwNullPointerException
. - Arrays.asList(): Allows
null
elements.
3. Backing
- List.of(): Creates a new, independent, immutable list. Changes to any array used to construct elements do not affect the list.
- Arrays.asList(): The returned list is backed by the provided array, so changes to the array will reflect in the list, and vice versa.
4. Use Cases
- List.of(): Best for short, immutable lists—like constants or configuration data.
- Arrays.asList(): Best for quickly wrapping an array as a list when you might want to modify elements but don’t need to change the size.
5. Example
List<String> a = List.of("A", "B"); // Immutable, no nulls List<String> b = Arrays.asList("A", null); // Fixed-size, allows null a.set(0, "X"); // Throws UnsupportedOperationException b.set(0, "X"); // Works a.add("C"); // Throws UnsupportedOperationException b.add("C"); // Throws UnsupportedOperationException