title: Why can't the java Iterable interface take a generics wildcard? Or: why can't I an overriding iterator() method return an Iterator for a subclass?
body: <p>I have some classes: SearchResponse, SearchResponseHit, SpecialSearchResponse (extends SearchResponse) and SpecialSearchResponseHit (extends SearchResponseHit).</p>
  
  <p>SearchResponse look something like this:</p>
  
  <pre><code>public class SearchResponse implements Iterable&lt;SearchResponseHit&gt; {
  
      [...]
  
      public Iterator&lt;SearchResponseHit&gt; iterator() {
          return searchResponseHits.iterator();
      }
  }
  </code></pre>
  
  <p>This makes it possible for me to use an instance of SearchResponse in a foreach loop, like this:</p>
  
  <pre><code>for (SearchResponseHit hit : mySearchResponse) {
      [...]
  }
  </code></pre>
  
  <p>Now, what I want to do, but can't find out how, is to make this code compile when I have an instance of SpecialSearchResponse:</p>
  
  <pre><code>for (SpecialSearchResponseHit specialHit : mySpecialSearchResponse) {
      [...]
  }
  </code></pre>
  
  <p>This gives me the following compiler error:  </p>
  
  <pre><code>Type mismatch: cannot convert from element type SearchResponseHit to SpecialSearchResponseHit
  </code></pre>
  
  <p>If I try to add this code to SpecialSearchResponse:</p>
  
  <pre><code>public Iterator&lt;SpecialSearchResponseHit&gt; iterator() {
      [...]
  }
  </code></pre>
  
  <p>...I get the error:</p>
  
  <pre><code>The return type is incompatible with Iterable&lt;SearchResponseHit&gt;.iterator()
  </code></pre>
  
  <p>I have tried changing the method in SearchResponse to:</p>
  
  <pre><code>    public Iterator&lt;? extends SearchResponseHit&gt; iterator() {
          return searchResponseHits.iterator();
      }
  </code></pre>
  
  <p>...but this gives me the error:</p>
  
  <pre><code>The return type is incompatible with Iterable&lt;SearchResponseHit&gt;.iterator()
  </code></pre>
  
  <p>Then I tried changing the class definition to:</p>
  
  <pre><code>public class SearchResponse implements Iterable&lt;? extends SearchResponseHit&gt;
  </code></pre>
  
  <p>...but this gives me this error:</p>
  
  <pre><code>    The type SearchResponse cannot extend or implement Iterable&lt;? extends SearchResponseHit&gt;. A supertype may not specify any wildcard
  </code></pre>
  
  <p>What is the best (and prettiest) way to solve this? Or do I have to skip the foreach-method (and other functions that use the Iterable interface behind the scenes) and write a getSpecialIterator() method and then use the iterator directly?</p>
  
  <p>Regards
  /J</p>