您可以使用通配符:
public static List<STriple> listTriples(List<? extends SResource> subjects){ //... do stuff}新声明使用有 界通配符 ,表示通用参数将是
SResource或扩展它的类型。
作为接受
List<>这种方式的交换,“做某事”不能包括插入
subjects。如果您只是从
subjects方法中读取内容,那么此更改将为您提供所需的结果。
编辑 :要查看为什么需要通配符,请考虑以下(在Java中是非法的)代码:
List<String> strings = new ArrayList<String>();List<Object> objList = string; // Not actually legal, even though string "is an" objectobjList.add(new Integer(3)); // Oh no! We've put an Integer into an ArrayList<String>!
那显然不是类型安全的。但是,使用通配符,您 可以 执行以下操作:
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


