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");
};
}
}