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.
Iterable<E>. empty constructor Null safetyCreates an empty iterable. The empty iterable has no elements, and iterating it always stops immediately.
Overall: Java API has no mean to say if the iterator value may be null or not, unless by stating it explicitly in the documentation. In this case, nothing is stated, however good sense allows to think that a null iterator value will never be returned from Java API methods.
You can get an empty list of type Foo through the following syntax:
return Collections.<Foo>emptyList().iterator();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With