javagenericsgeneric-method

generic method does not compile in java


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; 
}

Solution

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

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

    For reference, the docs