Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java iterator over an empty collection of a parameterized type

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.

like image 926
miner49r Avatar asked May 04 '09 19:05

miner49r


People also ask

Can iterable be empty?

Iterable<E>. empty constructor Null safetyCreates an empty iterable. The empty iterable has no elements, and iterating it always stops immediately.

Can iterator be null in Java?

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.


1 Answers

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

return Collections.<Foo>emptyList().iterator(); 
like image 68
Alex B Avatar answered Sep 18 '22 17:09

Alex B