Java – when the signature of a method is defined as collection, why can’t a method adopt collection

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 that

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 told me that I had to use triples to use sresource objects.)

When indexresource is a subclass of sresource

public class IndexResource extends SResource{ 
// .... class code here
}

I thought it was possible, so maybe I did something wrong If you suggest, I can release more code

Solution

You can do this using wildcards:

public static List<STriple> listTriples(List<? extends SResource> subjects){
    //... do stuff
}

The new declaration uses bounded wildcards to indicate that the generic parameter will be sresource or the type that extends it

In exchange for accepting list < > In this way, "doing things" cannot include inserting topics If you only read the topic in the method, this change should get the results you want

Edit: to understand why wildcards are needed, consider this (illegal in Java) code:

List<String> strings = new ArrayList<String>();
List<Object> objList = string; // Not actually legal,even though string "is an" object
objList.add(new Integer(3)); // Oh no! We've put an Integer into an ArrayList<String>!

This is clearly not type safe However, with wilcards, you can do this:

List<String> strings = new ArrayList<String>();
string.add("Hello");
List<? extends Object> objList = strings; // Works!
objList.add(new Integer(3)); // Compile-time error due to the wildcard restriction
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>