to extend my departments private Libary I tried to implement a isBetween method. This method is generic and expects a Comparable
type T
for its minimum value, its maximum value, and for an varargs values. Its purpose is to examine if all values are within the specified range.
public static void main(String[] args) {
System.out.print(isBetween(1, 100, 200, 100, 1, 2));
}
@SafeVarargs
public static <T extends Comparable> boolean isBetween(T minimum, T maximum, T... values) {
for (T value : values) {
if (!(value.compareTo(minimum) >= 0 && value.compareTo(maximum) <= 0))
return false;
}
return true;
}
This works just fine. But the type T can contain any Comparable objects. A method call:
System.out.print(isBetween(1, 100, 200, 100, "How awkward", 2));
would also be accepted at compile-time. This is not typesafe at all and can't be accepted.
Two solutions came into my mind:
1. call the method like the following
System.out.print(Class.<Integer>isBetween(1, 100, 200, 100, 1, 2));
2. make one of my method parameters of type U
and extend type T
to type U
Both "solutions" do not seem to be very elegant. The first one requires to write additional code before you call the method and the second one seems like a hack.
Are there any more elegant ways to solve my problem?