[英]Why is it not possible to call List<Number> not with List<Integer> even if Integer extends Number?
I was wondering why is it not possible to call List<Number>
not with List<Integer
> even Integer is an extended class of the abstract class Number ? 我想知道为什么即使Integer是Number抽象类的扩展类,也无法通过List<Integer
>调用List<Number>
呢? There is a logical error as I could call a Method with the parameter Number also with Integer. 存在逻辑错误,因为我也可以使用整数来调用带有参数Number的Method。
public class Que
{
public void enterNumbers(List<Number> nummern)
{
for (Number number : nummern)
{
System.out.println(number + "\n");
}
}
public void enterNum(Number num)
{
System.out.println("This is a number " + num);
}
public static void main(String[] args)
{
Que que = new Que();
Integer myInteger = new Integer(7);
// possible (of course!)
que.enterNum(myInteger);
List<Integer> num = new ArrayList<Integer>();
num.add(4);
num.add(45);
Integer inte = new Integer(333);
num.add(inte);
// not possible !
que.enterNumbers(num);
}
}
To solve it I could work with List<?>
or List<? extends Number>
为了解决这个问题,我可以使用List<?>
或List<? extends Number>
List<? extends Number>
... so I don't need the solution I want to know the exact reason. List<? extends Number>
...,所以我不需要我想知道确切原因的解决方案。
The only solution I could think of List is bind with Number as a new Type of Data Structure. 我能想到的唯一解决方案是将Number绑定为新的数据结构类型。
Because you could eg add an instance of a different subclass of Number
to List<Number>
, eg, an object of type Double
, but obviously you shouldn't be allowed to add them to List<Integer>
: 因为您可以例如将Number
的另一个子类的实例添加到List<Number>
(例如, Double
类型的对象),但是显然您不应该被允许将它们添加到List<Integer>
:
public void myMethod(List<Number> list) {
list.add(new Double(5.5));
}
If you were allowed to call myMethod
with an instance of List<Integer>
this would result in a type clash when add
is called. 如果允许您使用List<Integer>
的实例调用myMethod
,则在调用add
时将导致类型冲突。
Generics are not co-varient like arrays. 泛型不是像数组那样的协变量。 This is not allowed because of type erasure. 由于类型擦除,因此不允许这样做。
Consider classes Vehicle
, Bike
and Car
. 考虑类Vehicle
, Bike
和Car
。
If you make 如果你做
public void addVehicle(List<Vehicle> vehicles){
vehicles.add(new Car());
}
Car
is of type Vehicle
, you can add a Car
into Vehicle
because it passes IS-A test. 这是有可能的,因为Car
属于Vehicle
类型,您可以将Car
添加到Vehicle
因为它通过了IS-A测试。 List<Bike>
to addVehicle(List<Vehicle> vehicles)
? 但是,如果允许传递List<Bike>
到addVehicle(List<Vehicle> vehicles)
怎么办? you would have added a Car
to bike list. 您应该将“ Car
添加到自行车”列表中。 which is plain wrong. 这是完全错误的。 So generics doesn't allow this. 因此,泛型不允许这样做。
Read about Polymorphism with generics 阅读有关泛型的多态性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.