Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generic code

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;
            }
        }
    }
like image 799
Sagar Avatar asked Jul 26 '15 15:07

Sagar


1 Answers

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>.

like image 60
Eran Avatar answered Sep 20 '22 14:09

Eran