Search code examples
javagenericscomparable

Fun with Java generics


Anybody knows how to write the piece of code below using generics AND avoiding compiler warnings ? (@SuppressWarnings("unchecked") is considered cheating).

And, maybe, checking via generics that the type of "left" is the same as the type of "right" ?

public void assertLessOrEqual(Comparable left, Comparable right) {
    if (left == null || right == null || (left.compareTo(right) > 0)) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
    }
}

Solution

  • This works with subclasses of Comparable types too:

    public <T extends Comparable<? super T>> void assertLessOrEqual(T left, T right) {
      if (left == null || right == null || left.compareTo(right) > 0) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
      }
    }