3

Possible Duplicate:
Comparing the values of two generic Numbers

I want to write some methods for testing Numbers (Long, Integer, etc) like this:

public static <T extends Number> boolean isBetween(T min, T max, T number) {
    return min.compareTo(number) <= 0 && max.compareTo(number) >= 0; 
}

But I'm getting a compile error saying:

The method compareTo(T) is undefined for the type T

How can I fix this?

Community
  • 1
  • 1
Bohemian
  • 412,405
  • 93
  • 575
  • 722

2 Answers2

3

Number doesn't implement Comparable (see Why doesn't java.lang.Number implement Comparable? for the rationale), but you can restrict yourself to the Numbers that do:

public static <T extends Number & Comparable<T>> boolean isBetween ...
Community
  • 1
  • 1
John Dvorak
  • 26,799
  • 13
  • 69
  • 83
0

You need to do the casting. the following should work

return ((Comparable<T>) min).compareTo(number) <= 0 && ((Comparable<T>) max).compareTo(number) >= 0;
Risin
  • 21
  • 3