Uwe Allner Uwe Allner - 4 months ago 19
Java Question

Why is it considered bad practice to define a covariant compareTo method?

Here's an example from my code:

Baseclass:

abstract class AbstractBase implements Comparable<AbstractBase> {
private int a;
private int b;

public int compareTo(AbstractBase other) {
// compare using a and b
}
}


Implementation:

class Impl extends AbstractBase {
private int c;

public int compareTo(Impl other) {
// compare using a, b and c with c having higher impact than b in AbstractBase
}


FindBugs reports this as an issue. But why is that? What could happen?

And how would I correctly implement a solution?

Answer

Impl#compareTo(Impl) is not overriding AbstractBase#compareTo(AbstractBase) since they don't have the same signature. In other words, it won't be called when using Collections#sort for example.