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
nullelements. - Returns a list with a fixed size.
2. Arrays.asList()
- Available since Java 1.2.
- Creates a mutable list backed by an array.
- Allows
nullelements. - 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 UnsupportedOperationExceptionSimilar Post: Java 9- Creating Collection using Factory Method of(…)
3. Summary
- Use
List.offor creating immutable lists with nonullelements. - Use
Arrays.asListfor creating mutable lists that allownullelements but have a fixed size.