Speaking Comparable

The SpeakingComparable interface is an extension of the interface Comparable. This interface adds some methods to perform comparing. The methods names are chosen in a more speaking fashion instead of the mathematical expressions = 0, < 0, > 0 etc.

On the other hand it's annoying to implement to whole bunch of methods. Therefore, there is an abstract adapter class which could be extended. Extending from a class is not always an option. In this cases, it's possible to create a SpeakingComparable wrapper for a Comparable.

To avoid overloading of Object#equals() the equals method is named equalsTo(). This will also support cases where equals is inconsistent with compareTo. The Javadoc of Comparable noted

  It is strongly recommended (though not required) that natural orderings be consistent with equals.
This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely"
when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In
particular, such a sorted set (or sorted map) violates the general contract for set (or map), which
is defined in terms of the equals method.

Usage

A class which extends the SpeakingComparableAdapter could be written like

1
2
3
4
5
6
7
8
9
10
11
12
13
private static class SpeakingComparableInteger extends SpeakingComparableAdapter<Integer> {
 
    private Integer value;
 
    SpeakingComparableInteger(int value) {
        this.value = Integer.valueOf(value);
    }
 
    @Override
    public int compareTo(Integer other) {
        return value.compareTo(other);
    }
}

To create a SpeakingComparable wrapper for a Comparable call the factory

1
SpeakingComparable<Integer> speakingComparable = Speaking.comparable(Integer.valueOf(1));