The Collections.emptyIterator() method in Java returns an immutable empty Iterator that contains no elements. It is useful when a method needs to return an Iterator but there are no elements to iterate over, avoiding the need to return null.
- The iterator contains no elements, so hasNext() always returns false.
- Helps prevent NullPointerException by returning an empty iterator instead of null.
import java.util.*;
public class EmptyIteratorExample {
public static void main(String[] args) {
Iterator<String> iterator = Collections.emptyIterator();
System.out.println(iterator.hasNext());
}
}
Output
false
Explanation: The iterator is empty, so it contains no elements and hasNext() returns false.
Syntax:
public static <T> Iterator<T> emptyIterator()
- Parameters: This method does not accept any parameters.
- Return Value: Returns an empty
Iteratorcontaining no elements. - Exceptions: This method does not throw any exceptions.
Example: Creating an Empty Iterator
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Create an empty iterator
Iterator<String> iterator =
Collections.emptyIterator();
System.out.println(iterator.hasNext());
}
}
Output
false
Explanation: The iterator is empty, so hasNext() returns false, indicating that there are no elements to iterate over.
Example: Iterating Over an Empty Iterator
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Create an empty iterator
Iterator<String> iterator =
Collections.emptyIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println("Iterator is empty.");
}
}
Output
Iterator is empty.
Explanation: Since the iterator contains no elements, the while loop is never executed, and the program directly prints "Iterator is empty."
Related Methods
| Method | Description |
|---|---|
| Collections.emptyEnumeration() | Returns an empty Enumeration. |
| Collections.emptyListIterator() | Returns an empty ListIterator. |
| Collections.emptyList() | Returns an immutable empty List. |
| Collections.emptySet() | Returns an immutable empty Set. |
| Collections.emptyMap() | Returns an immutable empty Map. |
Advantages
- Returns a safe empty Iterator instead of null.
- Prevents NullPointerException in iterator-based code.
- Reusable and memory-efficient.
- Useful when implementing APIs that return an Iterator.