Arrays.asList() vs. List.of() in Java
List.of
and Arrays.asList
are both used to create lists in Java, but they have some differences:
1. List.of()
- Introduced in Java 9.
- Creates an immutable list.
- Does not allow
null
elements. - Returns a list with a fixed size.
2. Arrays.asList()
- Available since Java 1.2.
- Creates a mutable list backed by an array.
- Allows
null
elements. - The size of the list is fixed, but the elements can be changed.
Example
// Using List.of
List<String> immutableList = List.of("a", "b", "c");
// immutableList.add("d"); // This will throw UnsupportedOperationException
// Using Arrays.asList
List<String> mutableList = Arrays.asList("a", "b", "c");
mutableList.set(0, "z"); // This is allowed
// mutableList.add("d"); // This will throw UnsupportedOperationException
Similar Post: Java 9- Creating Collection using Factory Method of(…)
3. Summary
- Use
List.of
for creating immutable lists with nonull
elements. - Use
Arrays.asList
for creating mutable lists that allownull
elements but have a fixed size.