Reputation: 5223
Out of these 2 methods inspect1 shows compilation error "Unexpected bound" and inspect2 works fine, why ?
public <U> void inspect1(List<U extends Number> u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}
public <U> void inspect2(List<? extends Number> u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}
Upvotes: 2
Views: 1830
Reputation: 44398
To make it work, this should be defined in the generic type method signature saying that U
can be any type that is a subclass of Number
:
public <U extends Number> void inspect1(List<U> u) {
// body
}
Also, note in the second method, the parameter U
is never used and should be as below. This says that any list of a subclass of Number
is accepted. No generic parameter U
is involved.
public void inspect2(List<? extends Number> u) {
// body
}
Is there going to be any difference between these 2 methods (inspect1 and inspect2) you have provided in the answer, or they are going to work exactly the same?
They practically do the same since you cannot extend Number
and the only types extending this class are (hope I got them all):
Double
, Float
, Short
, Integer
and Long
Upvotes: 3