Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 864
Uwe Allner Avatar asked Jun 18 '14 07:06

Uwe Allner


1 Answers

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.

like image 145
sp00m Avatar answered Sep 30 '22 20:09

sp00m