CodeQL documentation

Overloaded compareTo

ID: java/wrong-compareto-signature
Kind: problem
Severity: error
Precision: medium
Tags:
   - reliability
   - correctness
Query suites:
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Classes that implement Comparable<T> and define a compareTo method whose parameter type is not T overload the compareTo method instead of overriding it. This may not be intended.

Example

In the following example, the call to compareTo on line 17 calls the method defined in class Super, instead of the method defined in class Sub, because the type of a and b is Super. This may not be the method that the programmer intended.

public class CovariantCompareTo {
	static class Super implements Comparable<Super> {
		public int compareTo(Super rhs) {
			return -1;
		}
	}
	
	static class Sub extends Super {
		public int compareTo(Sub rhs) {  // Definition of compareTo uses a different parameter type
			return 0;
		}
	}
	
	public static void main(String[] args) {
		Super a = new Sub();
		Super b = new Sub();
		System.out.println(a.compareTo(b));
	}
}

Recommendation

To override the Comparable<T>.compareTo method, the parameter of compareTo must have type T.

In the example above, this means that the type of the parameter of Sub.compareTo should be changed to Super.

References