Question

How can I compare generic member with say a primitive type?

Say,

void method(T k) {
   if(k < 10) ...
}

Unlike C/C++ one cannot overload operators in Java, right? In order to evaluate the above snippet, do I have to cast k into the actual type? Is there a more elegant way to solve this than using casting?

Was it helpful?

Solution

Your generic type could be forced to implement a certain interface wich does the comparison in a seperate method. With this version your class T could also be dereived from another class.

public interface CompareToInt {

    public boolean less(int that);
}

Your class with your method:

public class Dummy<T extends CompareToInt> {

    void method(T k){
        if (k.less(10)){
            // ... do stuff
        }
    }
}

edit:

my solution was inspired by popalka's

OTHER TIPS

If your type T extends Number, use this information in class signature

public class Num<T extends Number> {

    void method(T a){
        if (a.intValue()<10){

        }

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top