I have a method that takes a list of SResource objects
public static List<STriple> listTriples(List<SResource> subjects){
//... do stuff
}
Why can’t I do this
List<IndexResource> resultsAsList = new ArrayList<IndexResource>();
resultsAsList.addAll(allResults.keySet()); // I could possible not use lists and just use sets and therefore get rid of this line, but that is a different issue
List<STriple> triples = new ArrayList<STriple>();
triples = TriplesDao.listTriples(resultsAsList);
(The compiler tells me I have to make triples use SResource objects.)
When IndexResource is a subclass of SResource
public class IndexResource extends SResource{
// .... class code here
}
I would have thought this has to be possible, so maybe I am doing something else wrong. I can post more code if you suggest it.
You can do it, using wildcards:
The new declaration uses a bounded wildcard, which says that the generic parameter will be either an
SResource, or a type that extends it.In exchange for accepting the
List<>this way, “do stuff” can’t include inserting intosubjects. If you’re just reading from thesubjectsin the method, then this change should get you the results you want.EDIT: To see why wildcards are needed, consider this (illegal in Java) code:
That’s obviously not typesafe. With wilcards, though, you can do this: