An object implementing Iterable
interface must have a method with this signature:
Iterator<T> iterator()
o being an Iterable
, is this code safe?
while(o.iterator().hasNext()) { ... }
In other terms, may iterator()
returns null in case there is nothing to iterate over?
EDIT:
1- As some of you point out, the iterator returned is different each time o.iterator() is executed. Fair enough! I must agree that I had forgotten this point when writing the question.
Let's say this line is rewritten:
Iterator<String> it = o.iterator();
....
....
while(it.hasNext() {...}
2- As some of you point out, this is bad programming practice to return null when the documentation for Iterable.iterator() says: "Returns an iterator over a set of elements of type T."
However my question is about whether returning null is prevented directly or indirectly by some 'contract' in the Java API documentation. To me "Returns an iterator over a set of elements of type T" doesn't prevent returning null. I may be wrong.
Conclusion from your answers and additional research
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. This may be different for API written by individuals.
- Nothing in the documentation prevents the returned value to be null (e.g. @NotNull)
- In the Javadoc, many @Return are explicit when null is also to be anticipated
- This question is about null return values in general, interesting.
- I've found an attempt for a language to describe APIs, though it for .NET