public static <T> void myMethod(int a, Consumer<T> consumer){// Some code}
public static void myMethod(int a, Consumer<T> consumer){// Some code}
Difference between 'void' and '<T> void'
There is no such thing as <T> void
. These are two entirely separate declarations (<T>
and void
) that happen to be next to each other:
public static <T> void myMethod(int a, Consumer<T> consumer){/* Some code */}
// │ │
// │ └─ Declaration of method's return type
// │
// └────── Declaration of a generic type which is used only
// by this method
And how is this different?
public static void myMethod(int a, Consumer<T> consumer){/* Some code */}
In the above line, <T>
is not declared anywhere, so the declaration will not compile. (If the method were not static, it could use the <T>
declared on the enclosing class, assuming the enclosing class declares a <T>
type.)