I have several classes: SearchResponse, SearchResponseHit, SpecialSearchResponse (extends SearchResponse) and SpecialSearchResponseHit (extends SearchResponseHit).
SearchResponse looks something like this:
public class SearchResponse implements Iterable<SearchResponseHit> { [...] public Iterator<SearchResponseHit> iterator() { return searchResponseHits.iterator(); } }
This allows me to use an instance of SearchResponse in a foreach loop, for example:
for (SearchResponseHit hit : mySearchResponse) { [...] }
Now, what I want to do, but cannot figure out how to make this code compile when I have an instance of SpecialSearchResponse:
for (SpecialSearchResponseHit specialHit : mySpecialSearchResponse) { [...] }
This gives me the following compiler error:
Type mismatch: cannot convert from element type SearchResponseHit to SpecialSearchResponseHit
If I try to add this code to SpecialSearchResponse:
public Iterator<SpecialSearchResponseHit> iterator() { [...] }
... I get an error message:
The return type is incompatible with Iterable<SearchResponseHit>.iterator()
I tried changing the method in SearchResponse to:
public Iterator<? extends SearchResponseHit> iterator() { return searchResponseHits.iterator(); }
... but this gives me an error:
The return type is incompatible with Iterable<SearchResponseHit>.iterator()
Then I tried changing the class definition to:
public class SearchResponse implements Iterable<? extends SearchResponseHit>
... but this gives me this error:
The type SearchResponse cannot extend or implement Iterable<? extends SearchResponseHit>. A supertype may not specify any wildcard
What is the best (and most beautiful) way to solve this problem? Or do I need to skip the foreach method (and other functions that use the Iterable interface behind the scenes) and write the getSpecialIterator () method and then use the iterator directly?
Relations / J