title: Iterable: may iterator() returns null in case there is nothing to iterate over?
body: <p>An object implementing <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html" rel="nofollow noreferrer"><code>Iterable</code></a> interface must have a method with this signature:</p>
  
  <pre><code>Iterator&lt;T&gt; iterator()
  </code></pre>
  
  <p>o being an <code>Iterable</code>, is this code safe?</p>
  
  <pre><code>while(o.iterator().hasNext()) { ... }
  </code></pre>
  
  <p>In other terms, may <code>iterator()</code> returns null in case there is nothing to iterate over?</p>
  
  <p>EDIT:</p>
  
  <p>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.</p>
  
  <p>Let's say this line is rewritten:</p>
  
  <pre><code>Iterator&lt;String&gt; it = o.iterator();
  ....
  ....
  while(it.hasNext() {...}
  </code></pre>
  
  <p>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."</p>
  
  <p>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.</p>
  
  <p><strong>Conclusion from your answers and additional research</strong></p>
  
  <p>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.</p>
  
  <ul>
  <li>Nothing in the documentation prevents the returned value to be null (e.g. @NotNull)</li>
  <li>In the Javadoc, many @Return are explicit when null is also to be anticipated</li>
  <li><a href="https://stackoverflow.com/questions/411447/how-to-show-if-a-method-may-return-null?rq=1">This question</a> is about null return values in general, interesting.</li>
  <li>I've found <a href="http://research.microsoft.com/en-us/projects/specsharp/#overview" rel="nofollow noreferrer">an attempt</a> for a language to describe APIs, though it for .NET</li>
  </ul>