The Collections.emptyList() method of the java.util.Collections class returns an immutable empty List. The returned list contains no elements and cannot be modified. Any attempt to add, remove, or update elements in the returned list results in an UnsupportedOperationException.
- Does not require creating a new ArrayList object.
- Generic method that works with any object type.
- Commonly used to return an empty list instead of null.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = Collections.emptyList();
if (names.isEmpty()) {
System.out.println("No records found.");
}
}
}
Output
No records found.
Explanation: This example uses Collections.emptyList() to safely return an empty list and checks whether it contains any elements using the isEmpty() method.
Syntax
public static final <T> List<T> emptyList()
- Parameters: This method does not accept any parameters.
- Return Value: Returns an immutable empty
Listof the specified type. - Exception: UnsupportedOperationException: Thrown if an attempt is made to modify the returned empty list.
Example: Creating an Empty List using emptyList()
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Create an immutable empty list
List<String> list = Collections.emptyList();
// Display the list
System.out.println("Empty List: " + list);
// Check its size
System.out.println("Size: " + list.size());
}
}
Output
Empty List: [] Size: 0
Explanation: This example creates an immutable empty list using Collections.emptyList(). Since the list contains no elements, its size is 0.
Example: Attempting to Modify an Empty List
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Create an immutable empty list
List<Integer> list = Collections.emptyList();
try {
// Attempt to add an element
list.add(10);
}
catch (UnsupportedOperationException e) {
System.out.println("Exception: " + e);
}
}
}
Output
Exception: java.lang.UnsupportedOperationException
Collections.emptyList() and new ArrayList<>()
| Collections.emptyList() | new ArrayList<>() |
|---|---|
| Returns an immutable empty list. | Returns a mutable empty list. |
| Cannot add or remove elements. | Elements can be added or removed. |
| Reuses a shared empty list instance. | Creates a new object every time. |
| Suitable for returning read-only empty collections. | Suitable when modifications are required. |
Advantages of emptyList()
- Returns a reusable immutable empty list.
- Avoids unnecessary object creation.
- Safer than returning null from methods.
- Improves code readability and reliability.
- Supports generic type safety.