I am new to generics. You can see I am repeating some code after knowing the exact type of val
, filterSmall
, filterGreat
. I want to write generic code for comparing val
against filter values. I could write something like this
private <T> boolean compareAgainstFilters(T val, T filterSmall, T filterGreat) {
if (!(filterSmall != null && filterSmall <= val)) {
return true;
}
if (!(filterGreat != null && val <= filterGreat)) {
return true;
}
return true;
}
but at compile time, java wouldn't know if the <=
operator is valid for type T
.
I don't want to repeat the code, so how can I achieve that?
if (value != null) {
switch (value.getClass().getName()) {
case "java.lang.Long":
Long filterSmall = (Long) filterSmaller;
Long filterGreat = (Long) filterGreater;
Long val = (Long) value;
if (!(filterSmall != null && filterSmall <= val)) {
return true;
}
if (!(filterGreat != null && val <= filterGreat)) {
return true;
}
break;
case "java.lang.Float":
Float filterSmallFloat = (Float) filterSmaller;
Float filterGreatFloat = (Float) filterGreater;
Float valFloat = (Float) value;
if (!(filterSmallFloat != null && filterSmallFloat <= valFloat)) {
return true;
}
if (!(filterGreatFloat != null && valFloat <= filterGreatFloat)) {
return true;
}
}
}
You can use the Comparable
interface for comparing numbers, since all the wrapper classes of numeric primitives implement it :
private <T extends Comparable<T>> boolean compareAgainstFilters(T val, T filterSmall, T filterGreat) {
if (!(filterSmall != null && filterSmall.compareTo(val)<=0)) {
return true;
}
if (!(filterGreat != null && val.compareTo(filterGreat)<=0)) {
return true;
}
return true;
}
<T extends Comparable<T>>
restricts the types that can be used as type arguments instead of T. In this case they are required to implement Comparable<T>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With