Java Generic type : what is the difference between
(1) List <? extends Number>
(2) List <T extends Number>
as per my understanding
(1) List <? extends Number> is the
Readonly List of "unknown" data type with super class "Number". we can read the element only but can not add
(2) List <T extends Number>
List of data type with super class "Number". we can read and add the elements into the list
Please see the below code example
class TestGen{
public static void main(String[] args) {
double result = 0.0;
List<Integer> intList = new ArrayList<Integer>();
intList.add(10);
intList.add(20);
intList.add(30);
result = TestGen.sumOfList1(intList);
System.out.println("Result=" + result);
result = TestGen.sumOfList2(intList);
System.out.println("Result=" + result);
}
public static double sumOfList1(List<? extends Number> list) {
double s = 0.0;
for (Number n : list)
s += n.doubleValue();
return s;
}
public static <T extends Number> double sumOfList2(List<T> list) {
double s = 0.0;
// getting error while trying to add new element
// list<T> is not applicable for argument(Integer) : Why ?
list.add(new Integer(40));
for (Number n : list)
s += n.doubleValue();
return s;
}
}
When I am trying to add the Integer (or even Number object) into the sumOfList2 then getting the error. Please explain what is wrong here ?