-2

I am studying generic methods, i just come to this code, and I can not seem to figure out why the following line of code does not compile

public static T genMethod(T t) {
        return t; 
}
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
  • 3
    It's not generic. The error message should tell you that it can't resolve the symbol T. https://docs.oracle.com/javase/tutorial/extra/generics/methods.html – JB Nizet Oct 25 '18 at 18:13
  • If `T` is not a type you've imported, then you should declare it as a _type parameter_ ``. – LuCio Oct 25 '18 at 18:20

1 Answers1

3

You need to include <T> in the method signature:

public static <T> T genMethod(T t) {
    return t; 
}

For reference, the docs

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
  • please explain, i got the solution before but i need explanation – The Scientific Method Oct 25 '18 at 18:15
  • 3
    @TheScientificMethod I posted a link to the tutorial about generics in the first comment under your question. Apply The Rational Method: click the link, and read the tutorial. – JB Nizet Oct 25 '18 at 18:19
  • @JBNizet why I need to put that, the return type is matching with with type of object i am returning – The Scientific Method Oct 25 '18 at 18:27
  • 2
    Because that's what tells the compiler that T is not an actual concrete type, i.e. a class whose real name is T, but the generic type of the method. Without the , the method is not generic, and the compiler is thus looking for a class named T, hence the error message you get. – JB Nizet Oct 25 '18 at 18:28
  • @JBNizet thanks, please include this as answer, it does explain very well. – The Scientific Method Oct 25 '18 at 18:32