user3135757 user3135757 - 1 year ago 56
Java Question

Integer extends Number

Now in this code where I can obviously iterate through the list as

Integers
and
Double
are both extended from
Number
super class is working perfectly as intended:

public static void viewList(List<? extends Number> num) {
for (Number num1 : num) {
System.out.println(num1);
}
}

public static void main(String[] args) {

List<Integer> arl = new ArrayList<Integer>();
viewList(arl);

}


but here to add the data into the collection instead would never work as Integer and Double are not Superclass of Number and

I understand the PECS concept (Producer Extends Consumer Super)

public static void addList(List<? super Number> num) {
num.add(1);
num.add(2);
num.add(3);
}

public static void main(String[] args) {

List<Integer> arl = new ArrayList<Integer>();
addList(arl);

}


As expected I am getting an error here, so how to do it in the right way So I will be able to add whatever type I want in the collection?

Answer Source

A List<? super Number> means a list of Number, or of a type that is above Number in the inheritance tree. So

  • List<Number> qualifies: you may add any type of Number to a List<Number>
  • List<Serializable> qualifies: you may add any type of Number to a List<Serializable>
  • List<Object> qualifies: you may add any type of Number to a List<Object>
  • List<Integer> does NOT qualify: you may NOT add any type of Number to a List<Integer>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download