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 ? There is a logical error as I could call a Method with the parameter Number also with Integer.
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>
... so I don't need the solution I want to know the exact reason.
The only solution I could think of List is bind with Number as a new Type of Data Structure.
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.
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());
}
Car
is of type Vehicle
, you can add a
Car
into Vehicle
because it passes IS-A test.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With