Question
What are the differences between List.of and Arrays.asList in Java?
List<String> strings = List.of("first", "second");
List<Integer> nums = Arrays.asList(1, 2, 3);
Answer
In Java, both List.of and Arrays.asList are methods used to create lists. However, they have significant differences in terms of mutability, performance, and use cases. Understanding these differences can help developers choose the right method for their specific needs.
List<Integer> immutableList = List.of(1, 2, 3); // Throws UnsupportedOperationException when trying to modify
List<Integer> mutableList = Arrays.asList(1, 2, 3); // Can be modified (size is fixed but elements can change)
Causes
- **Mutability**: Lists created with List.of are immutable, meaning they cannot be modified after creation. Conversely, lists created with Arrays.asList are mutable and allow changes such as adding or removing elements.
- **Performance**: List.of has better performance characteristics compared to Arrays.asList, especially for small lists, as it performs optimally while consuming less memory due to its immutable nature.
- **Null Values**: List.of does not allow null elements, and attempting to create a list with null values will throw a NullPointerException. Arrays.asList, however, allows null elements.
Solutions
- Use List.of when you need an immutable list, which provides guarantees about its contents not changing over time.
- Choose Arrays.asList when you require a mutable list, especially in scenarios where elements may need to be added or modified after creation.
Common Mistakes
Mistake: Assuming that List.of returns a mutable list.
Solution: Remember that List.of returns an immutable list. Attempting to modify it (e.g., adding or removing elements) will throw UnsupportedOperationException.
Mistake: Using List.of with null values.
Solution: Avoid using List.of with any null elements to prevent a NullPointerException.
Helpers
- Java List.of
- Java Arrays.asList
- difference between List.of and Arrays.asList
- Java list creation methods
- mutable vs immutable lists in Java