Learnitweb

Java Collections.singleton() and Collections.emptySet() Tutorial

The Collections class in Java provides several utility methods to create predefined, immutable collection objects. Two commonly used methods are:

  1. Collections.singleton(T element) – Creates an immutable Set containing a single specified element.
  2. 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.
  • 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

  1. Immutable: Cannot add, remove, or modify elements.
  2. Size: Always 1.
  3. Null Element: Allowed (i.e., you can do Collections.singleton(null)).
  4. Performance: Very memory-efficient; internally implemented as a specialized singleton set.

1.5 Use Cases

  1. Passing single-element sets to APIs that expect a Set.
  2. Immutable collections to prevent modification.
  3. 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.
  • 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

  1. Immutable: Cannot be modified.
  2. Size: Always 0.
  3. Memory Efficiency: Single shared instance is returned; does not create a new object each time.
  4. Type-Safe: Returns a Set<T> to maintain generic type safety.

2.5 Use Cases

  1. Return an empty Set instead of null to avoid NullPointerException.
  2. Default immutable sets in APIs.
  3. Placeholder in algorithms where a set is required, but no elements are present.

3. Comparison Table

FeatureCollections.singleton()Collections.emptySet()
Size10
MutabilityImmutableImmutable
Null Element AllowedYesN/A (empty)
Use CaseSingle-element immutable setEmpty immutable set
Memory UsageMinimalShared 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

  1. Both singleton and emptySet return immutable sets.
  2. Attempting modifications like add, remove, or clear will throw UnsupportedOperationException.
  3. Use them to avoid null, improve memory efficiency, and ensure immutability.
  4. singleton is for one element, emptySet is for no elements.
  5. Both are frequently used in API design, caching, default values, and immutable collections.