Reputation: 2434
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
}
}
}
Upvotes: 0
Views: 78
Reputation: 2260
Use the interface for value
e.g.
public class Tree<T> implements Comparable<T> {
private Comparable<T> value;
@Override
public int compareTo(T o) {
// TODO Auto-generated method stub
if (value != null) {
return value.compareTo(o);
}
return 0;
}
}
Upvotes: 0
Reputation: 12776
You need to refine the generic type argument to Tree<T extends Comparable<T>>
-- otherwise the compiler has no idea that your T
object has a compareTo(T t)
method defined for it.
Upvotes: 4
Reputation: 160321
The signature for a generic compareTo should be (T arg0), not a plain Objct.
Upvotes: 0