0

I have a class which uses a generic type parameter. I want to write a method that only executes if the type parameter is Integer.

The specific scenario I am getting this question from is as follows: My assignment is to write a method, range(), for an AVLtree class which returns the difference of the minimum and maximum values of the tree. I tried returning maxNode.getE() - minNode.getE(), but this gives me a compiler error saying

error: bad operand types for binary operator '-'
                   return max.getE()-min.getE();
                                    ^
  first type:  E
  second type: E
  where E is a type-variable:
    E extends Comparable<? super E> declared in class AVLtreeCC

So is it possible to write a method that only executes when "E" is Integer.

The code below gives a visualization of what I am trying to acheive. I know T instanceof Integer will give a compiler error. I am trying to figure out what class T is.

class myClass<T>{
    void foo(){
        if(T instanceof Integer){
            ...
        }
        else{
            System.out.println("T is not of the Integer class, so this method will not work");
        };
    }
}
  • You can't test the type of `T` with `instanceof` because of [type erasure](https://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens). Having an instance method which only works when the type argument is only one of a subset of all valid type arguments is dubious at best. If you need such an instance method then force `T` to be compatible by declaring the appropriate bounds. – Slaw Nov 09 '19 at 03:25
  • What about having a static method which only accepts instances of `MyClass`? As in, `static int range(MyClass obj) { ... }`. Though what about all the other subtypes of `Number`? – Slaw Nov 09 '19 at 03:27
  • The static method is a great idea, and it works. – Caleb Chang Nov 09 '19 at 14:40

0 Answers0