Java 为什么这些继承的类型用作参数化类型不兼容的类型?
我对参数化集合的理解是,如果要使用参数化类型的子类型,则需要将集合声明为Java 为什么这些继承的类型用作参数化类型不兼容的类型?,java,generics,inheritance,collections,Java,Generics,Inheritance,Collections,我对参数化集合的理解是,如果要使用参数化类型的子类型,则需要将集合声明为collection,因为您可以将Box添加到Box,这将违反bananabox的完整性 public interface Apple extends Fruit {} //... Box<Apple> apples = new Box<>(); // this is legal Box<? extends Fruit> fruits = apples; // this is lega
collection,因为您可以将Box
添加到Box
,这将违反bananabox
的完整性
public interface Apple extends Fruit {}
//...
Box<Apple> apples = new Box<>(); // this is legal
Box<? extends Fruit> fruits = apples; // this is legal
Collection<Box<Banana>> bananaBoxes = new ArrayList<>();
Collection<Box<? extends Fruit>> boxes = bananaBoxes; //if this were legal...
boxes.add(fruits); //then this would be legal
//and this would be a type violation:
Box<Banana> bananas = bananaBoxes.iterator().next();
Apple扩展水果的公共接口{}
//...
苹果盒子=新盒子();//这是合法的
Box因为您可以将框
添加到框
,这将违反bananabox
的完整性
public interface Apple extends Fruit {}
//...
Box<Apple> apples = new Box<>(); // this is legal
Box<? extends Fruit> fruits = apples; // this is legal
Collection<Box<Banana>> bananaBoxes = new ArrayList<>();
Collection<Box<? extends Fruit>> boxes = bananaBoxes; //if this were legal...
boxes.add(fruits); //then this would be legal
//and this would be a type violation:
Box<Banana> bananas = bananaBoxes.iterator().next();
Apple扩展水果的公共接口{}
//...
苹果盒子=新盒子();//这是合法的
盒子
error: incompatible types
required: Collection<Box<? extends Fruit>>
found: Collection<Box<Banana>>
public interface Apple extends Fruit {}
//...
Box<Apple> apples = new Box<>(); // this is legal
Box<? extends Fruit> fruits = apples; // this is legal
Collection<Box<Banana>> bananaBoxes = new ArrayList<>();
Collection<Box<? extends Fruit>> boxes = bananaBoxes; //if this were legal...
boxes.add(fruits); //then this would be legal
//and this would be a type violation:
Box<Banana> bananas = bananaBoxes.iterator().next();
Collection<? extends Box<? extends Fruit>> boxes = bananaBoxes;