Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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.

like image 891
Fendrix Avatar asked Aug 29 '13 14:08

Fendrix


2 Answers

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.

like image 139
Thomas Avatar answered Oct 19 '22 05:10

Thomas


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

like image 8
Prasad Kharkar Avatar answered Oct 19 '22 05:10

Prasad Kharkar