Java Java7

Collections.emptyIterator() and emptyListIterator()

Collections.emptyIterator() and emptyListIterator()

Collections.emptyIterator() and emptyListIterator()

Java 7 added convenience methods to the Collections class to return empty iterators, list iterators, and enumeration objects.

How it Works

These methods provide a type-safe way to return an empty iterator instead of returning null or creating a full collection just to get an iterator. This is more memory-efficient and prevents NullPointerExceptions.

Java Example

import java.util.*;

public class EmptyIteratorExample {
    public static void main(String[] args) {
        Iterator<String> it = Collections.emptyIterator();
        System.out.println("Has Next? " + it.hasNext());
    }
}

Output

Has Next? false

Key Points

  • Memory efficient
  • Type-safe empty iterators
  • Avoids null returns in APIs
  • Consistent with other empty collection methods
Topics: Java Java7
← Newer Post Older Post →