Reputation: 522
Im new to generics. Maybe my question is dumb and silly but why the following doesnt work?
public <T extends Integer> Integer methodA(T t){
return t = t + 1;
}
It says that Operator cannot be applied to 'T', 'int'. What should I do to make this code work?
Upvotes: 2
Views: 1832
Reputation: 5835
public class SomeClass {
public <T extends Integer> Integer methodA(T t) {
return t.intValue() + 1 ;
}
}
This should work fine
Upvotes: -1
Reputation: 120848
You could do:
return t + 1;
But generally your declaration T extends Integer
makes little sense, because Integer
is marked final
, so one cannot extend
it.
Upvotes: 2
Reputation: 393801
This will work
public <T extends Integer> Integer methodA(T t){
return t + 1;
}
The reason return t = t + 1;
doesn't work is that t+1
returns an int
that can only be auto-boxed to an Integer
. As far as the compiler knows, T
may be a sub-class of Integer
(even though there is no such thing, as Integer
is a final class), so it doesn't allow an assignment of any Integer
to a variable of type T
.
Upvotes: 4