Overloaded compareTo¶
ID: java/wrong-compareto-signatureKind: problemSecurity severity: Severity: errorPrecision: mediumTags: - quality - reliability - correctnessQuery suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
Classes that implementComparable<T> and define acompareTo method whose parameter type is notToverload thecompareTo method instead ofoverriding it. This may not be intended.
Example¶
In the following example, the call tocompareTo on line 17 calls the method defined in classSuper, instead of the method defined in classSub, because the type ofa andb isSuper. This may not be the method that the programmer intended.
publicclassCovariantCompareTo{staticclassSuperimplementsComparable<Super>{publicintcompareTo(Superrhs){return-1;}}staticclassSubextendsSuper{publicintcompareTo(Subrhs){// Definition of compareTo uses a different parameter typereturn0;}}publicstaticvoidmain(String[]args){Supera=newSub();Superb=newSub();System.out.println(a.compareTo(b));}}
Recommendation¶
Tooverride theComparable<T>.compareTo method, the parameter ofcompareTo must have typeT.
In the example above, this means that the type of the parameter ofSub.compareTo should be changed toSuper.
References¶
J. Bloch,Effective Java (second edition), Item 12. Addison-Wesley, 2008.
Java Language Specification:Overriding (by Instance Methods),Overloading.
The Java Tutorials:Overriding and Hiding Methods.