The emptyList() method in Java returns an immutable list that contains no elements. It is part of the java.util.Collections class and provides a convenient way to obtain an empty list, useful in scenarios where a method requires a list but no elements need to be provided.
Table of Contents
- Introduction
emptyList()Method Syntax- Examples
- Basic Usage of
emptyList() - Using
emptyList()in a Custom Method
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.emptyList() method returns a statically typed, immutable list that contains no elements. This method can be particularly useful in situations where you need to return a list from a method, but there are no elements to include. By using emptyList(), you can avoid returning null and prevent potential NullPointerException errors in your code.
Since the list returned by emptyList() is immutable, it cannot be modified. Any attempts to add, remove, or modify elements will result in an UnsupportedOperationException.
emptyList() Method Syntax
The syntax for the emptyList() method is as follows:
public static final <T> List<T> emptyList()
Parameters:
- This method does not take any parameters.
Returns:
- An immutable empty list.
Examples
Basic Usage of emptyList()
The following example demonstrates how to use the emptyList() method to obtain an immutable empty list.
Example
import java.util.Collections;
import java.util.List;
public class EmptyListExample {
public static void main(String[] args) {
// Obtain an empty list
List<String> emptyList = Collections.emptyList();
// Check if the list is empty
System.out.println("Is the list empty? " + emptyList.isEmpty());
// Attempt to iterate over the list
for (String element : emptyList) {
System.out.println(element);
}
// Attempt to modify the list (will throw UnsupportedOperationException)
try {
emptyList.add("New Element");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot add elements to an immutable list");
}
}
}
Output:
Is the list empty? true
Error: Cannot add elements to an immutable list
Using emptyList() in a Custom Method
You can use the emptyList() method to return an empty list from a custom method when there are no elements to provide.
Example
import java.util.Collections;
import java.util.List;
public class CustomMethodExample {
public static void main(String[] args) {
// Get a non-empty list of fruits
List<String> fruits = getFruits(true);
System.out.println("Fruits (non-empty): " + fruits);
// Get an empty list of fruits
fruits = getFruits(false);
System.out.println("Fruits (empty): " + fruits);
}
// Method to return a list of fruits based on a condition
public static List<String> getFruits(boolean hasFruits) {
if (hasFruits) {
return List.of("Apple", "Banana", "Cherry"); // Java 9+ feature to create an immutable list
} else {
return Collections.emptyList();
}
}
}
Output:
Fruits (non-empty): [Apple, Banana, Cherry]
Fruits (empty): []
Explanation:
-
Non-Empty List: When
hasFruitsistrue, thegetFruits()method returns a non-empty immutable list of fruits, using theList.of()method introduced in Java 9. -
Empty List: When
hasFruitsisfalse, the method returns an empty immutable list usingemptyList(), demonstrating its utility in cases where no elements need to be returned.
Real-World Use Case
Providing Default Empty Lists in APIs
In API development, it is common to have methods that return lists. Using emptyList() can provide a safe default when there are no elements to return, avoiding null values and potential errors.
Example
Imagine a scenario where you have an API method that retrieves a list of users based on specific criteria. If no users meet the criteria, you can return an empty list instead of null.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class User {
String name;
int id;
User(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public String toString() {
return name + " (ID: " + id + ")";
}
}
public class UserService {
// Method to get a list of users based on a condition
public List<User> getUsers(boolean hasUsers) {
if (hasUsers) {
List<User> users = new ArrayList<>();
users.add(new User("Alice", 101));
users.add(new User("Bob", 102));
return users;
} else {
return Collections.emptyList();
}
}
public static void main(String[] args) {
UserService userService = new UserService();
// Retrieve a non-empty list of users
List<User> users = userService.getUsers(true);
System.out.println("Users (non-empty): " + users);
// Retrieve an empty list of users
users = userService.getUsers(false);
System.out.println("Users (empty): " + users);
}
}
Output:
Users (non-empty): [Alice (ID: 101), Bob (ID: 102)]
Users (empty): []
Explanation:
-
Non-Empty List: When
hasUsersistrue, thegetUsers()method returns a list of users, demonstrating how lists can be populated with elements when they are available. -
Empty List: When
hasUsersisfalse, thegetUsers()method returns an empty list usingemptyList(), ensuring that the method handles cases with no users correctly.
Conclusion
The Collections.emptyList() method is a useful utility for obtaining an immutable empty list in Java. By providing a typesafe, empty list, it helps prevent NullPointerException errors and ensures that your code handles cases where no elements are present gracefully. This method is particularly valuable when implementing APIs or methods that require lists but may not always have elements to return, enhancing the robustness and maintainability of your Java applications.