0

Why the below code is showing a compilation error. Doesn't extend mean it can take any subclass of Number, Also compilation is shown in the add method not while defining the List if it doesn't support this construct it should show compilation error while declaring.

List<? extends Number> list = new ArrayList<Integer>();
list.add(1)
garg10may
  • 5,794
  • 11
  • 50
  • 91

1 Answers1

0

Number literals are of type int. Using construction <? extends Number> you ensure, that you can pass only instances of Number class, or any classes, that Number inherits from (that is java.lang.Object). If you want to add subtypes of Number class, e.g. Integers you should use <? super Number> (it means: for whose Number is a super class) You may want to use:

List<? super Number> list = new ArrayList<>();
list.add(1); //no compile-time error

However, if you want to use elements of the collection, you may use them as instances of classes that extends Number class.

    List<? super Number> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    print(list);

    List<Object> objs = new ArrayList<>();
    objs.add(1);
    print(objs);

    List<Number> nums = new ArrayList<>();
    nums.add(1);
    print(nums);
}

public static void print(List<? super Number> list){ // you can pass List of instances of type Number or upper
    for(Object num: list){ // but you have to refer to them as Objects (it is an upper class of Number
        System.out.println(num);
    }
}
R-tooR
  • 106
  • 4