Anton Kolosok
Anton Kolosok

Reputation: 522

Java generics method <T extends Integer> +1

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

Answers (3)

public class SomeClass {

  public <T extends Integer> Integer methodA(T t) {
    return t.intValue() + 1 ;
  }
}

This should work fine

Upvotes: -1

Eugene
Eugene

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

Eran
Eran

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

Related Questions