The problem i’m having is that javac thinks T doesnt implement compareTo(). So how can i do this while still staying “generic”. Wouldnt casting to specific type defeat the purpose of using generic type?
public class Tree<T> implements Comparable<T> {
private T value;
public T getValue() {
return value;
}
@Override
public int compareTo(T arg0) {
// TODO Auto-generated method stub
if (this.getValue() != null) {
return this.getValue().compareTo(arg0); // compilation problem
}
}
}
You need to refine the generic type argument to
Tree<T extends Comparable<T>>— otherwise the compiler has no idea that yourTobject has acompareTo(T t)method defined for it.