The Collections class in Java provides several utility methods to create predefined, immutable collection objects. Two commonly used methods are:
Collections.singleton(T element)– Creates an immutable Set containing a single specified element.Collections.emptySet()– Creates an immutable, empty Set.
Both are part of the java.util.Collections class and are often used in scenarios where read-only sets are needed or to reduce object creation overhead.
1. Collections.singleton(T element)
1.1 Overview
- Returns a Set containing exactly one element.
- The returned Set is immutable:
- Attempting to add, remove, or modify elements will throw
UnsupportedOperationException.
- Attempting to add, remove, or modify elements will throw
- Useful for wrapping a single object as a Set to pass to APIs expecting a Set.
- Returns a Set that preserves the single element in iteration.
1.2 Syntax
public static <T> Set<T> singleton(T element)
- T: Type of the element.
- element: The object to include in the set.
1.3 Example Usage
Set<String> singleSet = Collections.singleton("Java");
System.out.println(singleSet); // [Java]
for (String s : singleSet) {
System.out.println(s); // Java
}
// Attempting to modify the set throws exception
try {
singleSet.add("Python"); // UnsupportedOperationException
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify singleton set");
}
1.4 Characteristics
- Immutable: Cannot add, remove, or modify elements.
- Size: Always
1. - Null Element: Allowed (i.e., you can do
Collections.singleton(null)). - Performance: Very memory-efficient; internally implemented as a specialized singleton set.
1.5 Use Cases
- Passing single-element sets to APIs that expect a
Set. - Immutable collections to prevent modification.
- Testing and examples, where a single element is required.
2. Collections.emptySet()
2.1 Overview
- Returns an empty, immutable Set.
- The returned Set is always empty and immutable:
- Attempting to add or remove elements will throw
UnsupportedOperationException.
- Attempting to add or remove elements will throw
- Often used to avoid returning null from methods that return a Set when there are no elements.
2.2 Syntax
public static final <T> Set<T> emptySet()
- Returns a Set with zero elements.
- Generic type
<T>ensures type safety when used with generic APIs.
2.3 Example Usage
Set<String> emptySet = Collections.emptySet();
System.out.println(emptySet); // []
for (String s : emptySet) {
System.out.println(s); // (nothing is printed)
}
// Attempting to modify the set throws exception
try {
emptySet.add("Java"); // UnsupportedOperationException
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify empty set");
}
2.4 Characteristics
- Immutable: Cannot be modified.
- Size: Always
0. - Memory Efficiency: Single shared instance is returned; does not create a new object each time.
- Type-Safe: Returns a
Set<T>to maintain generic type safety.
2.5 Use Cases
- Return an empty Set instead of
nullto avoidNullPointerException. - Default immutable sets in APIs.
- Placeholder in algorithms where a set is required, but no elements are present.
3. Comparison Table
| Feature | Collections.singleton() | Collections.emptySet() |
|---|---|---|
| Size | 1 | 0 |
| Mutability | Immutable | Immutable |
| Null Element Allowed | Yes | N/A (empty) |
| Use Case | Single-element immutable set | Empty immutable set |
| Memory Usage | Minimal | Shared instance |
4. Practical Examples
4.1 Passing Single Elements to APIs
void process(Set<String> items) {
System.out.println(items);
}
process(Collections.singleton("Java")); // [Java]
4.2 Returning Empty Sets from Methods
Set<String> findTags(String keyword) {
// If no tags found, return empty set instead of null
return Collections.emptySet();
}
4.3 Immutable Configurations
Set<String> supportedFormats = Collections.singleton("PDF");
// Prevents accidental modification
5. Key Points to Remember
- Both
singletonandemptySetreturn immutable sets. - Attempting modifications like
add,remove, orclearwill throwUnsupportedOperationException. - Use them to avoid null, improve memory efficiency, and ensure immutability.
singletonis for one element,emptySetis for no elements.- Both are frequently used in API design, caching, default values, and immutable collections.
