For objects a and b implementing the Comparable interface I want to avoid having code like
if (a.compareTo(b) > 0) {
...
}
instead, I am looking for helper methods like
if (a.isGreaterThan(b)) {
...
}
This would help me a lot for not always having to look up the definition of the return value of compareTo(T o):
Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Really helpful would be 5 different methods:
Instead of use potential helper method:
a.compareTo(b) < 0 a.isLessThan(b)
a.compareTo(b) <= 0 a.isLessOrEqualTo(b)
a.compareTo(b) == 0 a.isEqualTo(b)
a.compareTo(b) >= 0 a.isGreaterOrEqualTo(b)
a.compareTo(b) > 0 a.isGreaterThan(b)
Are there any helper methods like this in the JDK or other libraries that provide this kind of functionality?
The equals
method exists for every object. The rest you would have to create yourself. You could create an interface that has these methods so all the children would have them.
This should work:
public interface IComparable<T> extends Comparable<T> {
boolean isLessThan(T other);
boolean isLessOrEqualTo(T other);
boolean isGreaterOrEqualTo(T other);
boolean isGreaterThan(T other);
}
You could add default methods for each of the above methods. Like so:
public interface IComparable<T> extends Comparable<T> {
default boolean isLessThan(T other) {
return compareTo(other) < 0;
}
default boolean isLessOrEqualTo(T other) {
return compareTo(other) <= 0;
}
default boolean isGreaterOrEqualTo(T other) {
return compareTo(other) >= 0;
}
default boolean isGreaterThan(T other) {
return compareTo(other) > 0;
}
}