Java iterator over an empty collection of a parameterized type

collectionsiteratorjava

In Java, I need to return an Iterator from my method. My data comes from another object which usually can give me an iterator so I can just return that, but in some circumstances the underlying data is null. For consistency, I want to return an "empty" iterator in that case so my callers don't have to test for null.

I wanted to write something like:

public Iterator<Foo> iterator() {
   if (underlyingData != null) {
      return underlyingData.iterator();  // works
   } else {
      return Collections.emptyList().iterator();  // compiler error
   }
}

But the Java compiler complains about the returning Iterator<Object> instead of Iterator<Foo>. Casting to (Iterator<Foo>) doesn't work either.

Best Solution

You can get an empty list of type Foo through the following syntax:

return Collections.<Foo>emptyList().iterator();