Collections.empty* Factory Methods
You'll learn how to obtain immutable, zero-allocation empty collections using the Collections utility methods.
What Are Empty Factory Methods?
Sometimes you need to return or pass an empty collection—no elements at all. Instead of creating a new ArrayList() or HashSet() every time, Java provides special factory methods: Collections.emptyList(), Collections.emptySet(), and Collections.emptyMap(). These return immutable, shared empty instances that cost no extra memory.
Think of it like asking for an empty box. Instead of manufacturing a new box every time someone asks for an "empty one," you hand everyone the same permanent, sealed, empty display box. It's always empty, can't be modified, and saves resources.
Why Use Them?
When a method should return "no results," returning null forces callers to do null-checks. Returning an actual empty collection is cleaner and safer. These factory methods let you do that without allocating new objects:
List<String> emptyList = Collections.emptyList();
Set<Integer> emptySet = Collections.emptySet();
Map<String, Double> emptyMap = Collections.emptyMap();
All three return immutable empty collections. You can read from them (they're just empty), but any attempt to modify them throws UnsupportedOperationException.
Common Use Case
public List<String> findMatchingNames(String prefix) {
if (prefix == null) {
return Collections.emptyList(); // Safe, efficient default
}
// ... search logic
}
No memory allocation happens—Java reuses the same singleton instance every time.
Key Takeaway:
Use Collections.emptyList(), emptySet(), and emptyMap() to return immutable, zero-allocation empty collections instead of creating new instances or returning null.