Why is it not possible to call List not with List even if Integer extends Number?

后端 未结 2 1205

I was wondering why is it not possible to call List not with List> even Integer is an extended class of the abstract class

相关标签:
2条回答
  • 2021-01-13 06:57

    Because you could e.g. add an instance of a different subclass of Number to List<Number>, e.g., an object of type Double, but obviously you shouldn't be allowed to add them to 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.

    0 讨论(0)
  • 2021-01-13 06:59

    Generics are not co-varient like arrays. This is not allowed because of type erasure.

    Consider classes Vehicle, Bike and Car.

    If you make

    public void addVehicle(List<Vehicle> vehicles){
        vehicles.add(new Car());
    }
    
    • This is possible, because a Car is of type Vehicle, you can add a Car into Vehicle because it passes IS-A test.
    • But what if it was allowed to pass a List<Bike> to addVehicle(List<Vehicle> vehicles) ?

    you would have added a Car to bike list. which is plain wrong. So generics doesn't allow this.

    Read about Polymorphism with generics

    0 讨论(0)
提交回复
热议问题