为什么我super只能使用通配符而不使用类型参数?
例如,在Collection界面中,为什么toArray方法不是这样写的
interface Collection<T>{
<S super T> S[] toArray(S[] a);
}
Run Code Online (Sandbox Code Playgroud) 一个)
List<? super Shape> shapeSuper = new ArrayList<Shape>();
shapeSuper.add(new Square()); //extends from SHAP
shapeSuper.add(new DoubleSquare()); //extends from SQ
shapeSuper.add(new TripleSquare()); //extends from DS
shapeSuper.add(new Rectangle()); //extends from SHAP
shapeSuper.add(new Circle()); //extends from SHAP
for (Object object : shapeSuper) { ... }
Run Code Online (Sandbox Code Playgroud)
当我只能添加Shape及其衍生物时,为什么迭代必须是Objects?
B)
List<? super Shape> shapeSuper = new ArrayList<Object>();
shapeSuper.add(new Object()); //compilation error
Run Code Online (Sandbox Code Playgroud)
为什么上面的行会产生编译错误?
我明白了
Comparator < ? super T> comp
Run Code Online (Sandbox Code Playgroud)
它根据指定比较器引发的顺序返回给定集合的最大元素.但我不明白的目的
超级T
有人可以解释一下吗?
我今天碰到了一些我发现有问题的代码.这是一个简化的例子(不现实).
public interface IListable {
//returns first n items from list
public ArrayList getFirstNThings(int n);
//returns last n items from list
public ArrayList getLastNThings(int n);
}
Run Code Online (Sandbox Code Playgroud)
然后有一个像这样的实现者:
public GroceryList implements IListable {
private ArrayList<GroceryItem> groceries;
public GroceryList() {
this.groceries = new ArrayList<GroceryItem>();
}
public ArrayList<GroceryItem> getFirstNThings(int n) {
ArrayList<GroceryItem> firstNThings = new ArrayList<GroceryItem>();
for (int i=0; i < n; i++) {
firstNThings.add(this.groceries.get(i));
}
return firstNThings
}
public ArrayList<GroceryItem> getLastNThings(int n) {
ArrayList<GroceryItem> lastNThings = new ArrayList<GroceryItem>();
for (int i=this.groceries.size(); i …Run Code Online (Sandbox Code Playgroud) 我试图阅读和理解一些Java代码.这里是:
protected LoadTarget<? super PopulationLoadContext> createTarget(PopulationLoadContext context) {
return createTransactionalTargetGroup(RiskScoresTables.All_Tables);
}
Run Code Online (Sandbox Code Playgroud)
什么<? super PopulationLoadContext>意思?
是什么区别List<Integer>和List<? super Integer>。
哪个是好的做法或什么时候应该使用什么?
阅读书籍Java Generics and Collections.在Wildcards with Super一节中,我举了一个例子
public static <T> void copy(List<? super T> dst, List<? extends T> src) {
for (int i = 0; i < src.size(); i++) {
dst.set(i, src.get(i));
}
}
Run Code Online (Sandbox Code Playgroud)
它被称为这样:
Collections.<Number>copy(objs, ints);
Run Code Online (Sandbox Code Playgroud)
以上电话有效,其解释如下:
允许调用因为
objs有类型List<Object>,它是List<? super Number>(因为Object是Number通配符所需的超类型)的子ints类型List<Integer>,并且具有类型,它是List<? extends Number>(因为Integer是Number扩展通配符所需的子类型)的子类型
我的疑问是怎样List<Object>的一个亚型 List<? super Number>?