Greetings. In the Ultimate Java Part 3: Advance Topics module → Generics section → Generic Methods video, Mosh Explains the syntax for a generic method in a non-generic class. IntelliJ IDE is interpreting the return type as null in the code:
public static <T extends Comparable<T>> max(T first,T second){
return (first.compareTo(second) < 0) ? second : first;
This code does not produce this nor the following errors for Mosh:
Now here is a screen-capture of Moshs’ code for comparison:
- I tried changing the JDK and Language levels down to 17, but that did not help.
- I tried a different syntax, and that did not resolve it.
Any suggestions?
Thanks in advance.
I solved my own issue; it’s 4 A.M. and I’ve been coding since about 8 pm yesterday with no rest. So I didn’t notice the difference between my code and Moshs until I read this article from Oracle: Generic Methods (The Java™ Tutorials > Learning the Java Language > Generics (Updated)).
I noticed that
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method’s return type. For static generic methods, the type parameter section must appear before the method’s return type.
So I went back to Mosh and saw that the signature for his code is:
public static <T extends Comparable<T>> T max(T first, T second){}
I was missing the T
that is the RETURN TYPE; the public static <T extends Comparable<T>>
is only the “list of type parameters”.