Examples
1. Return a list from a single object
Option 1: Using Collections.singletonList(product)
Returns an immutable list containing exactly one element.
Product product = new Product();
List<Product> list = Collections.singletonList(product);Option 2: Using List.of(product) (Java 9+)
Returns an immutable list with the given element(s).
List<Product> list = List.of(product);Option 3: Using Arrays.asList(product)
Returns a mutable fixed-size list backed by an array.
List<Product> list = Arrays.asList(product);Option 4: Using new ArrayList<>(List.of(product)) (Java 9+)
Creates a mutable list with one element.
Option 5: Using new ArrayList<>(Collections.singletonList(product))
Similar to above, but compatible with Java 8. Useful if we are working in Java 8 but want a mutable list.
Recommended Approach
If we want immutability, prefer
Collections.singletonList()orList.of().If we want a modifiable list, wrap it in
new ArrayList<>().
2. UnsupportedOperationException or NullPointerException when adding element
When working with List in Java, especially when calling add() on a list retrieved via a getter method, we might encounter the following issues:
Scenario
Even though productGroup is not null, this line can throw either:
NullPointerExceptionUnsupportedOperationException
Root Causes
1. List is null
If the list is not initialized, calling add() will throw a NullPointerException.
Example:
2. List is immutable
If the list is initialized using one of the following:
Collections.emptyList()List.of(...)(Java 9+)Collections.unmodifiableList(...)
Then calling add() will throw an UnsupportedOperationException.
Solutions
Ensure the list is initialized and modifiable
Option 1: Initialize in the class
Option 2: Lazily initialize before use
Option 3: Create a modifiable copy if the list is unmodifiable
Last updated