I am new to generics and want to solve a little Task.
I want to give two Objects of type "V extends Comparable" to the class ComparePredicate and then check in method "isOk" if the int-value "value" of a Tree class is between these two Objects. I choosed the compareTo method because Integer and V should be of type comparable but the compiler gives an error. I think its just an syntactical problem.
So how do i need to write it correct. Hope you guys can help me. Thanks for your answers.
Class ComparePredicate
public class ComparePredicate<V extends Comparable<V>> implements TreePredicate<V> {
V minEle;
V maxEle;
public ComparePredicate(V minEle, V maxEle) {
this.minEle = minEle;
this.maxEle = maxEle;
}
@Override
public boolean isOk(Tree<V> tree) {
return minEle.compareTo(Integer.valueOf(tree.getValue())) > 0 &&
maxEle.compareTo(Integer.valueOf(tree.getValue())) < 1;
//COMPILER ERROR: "The method compareTo(V) in the type Comparable<V> is not applicable for the arguments (Integer)"
return false;
}
}
Class Tree
public class Tree<T> {
private int value;
private final Tree<T> left;
private final Tree<T> right;
public Tree(int v, Tree<T> l, Tree<T> r) {
this.value = v;
this.left = l;
this.right = r;
}
public int getValue() {
return this.value;
}
public Tree<T> getLeft() {
return this.left;
}
public Tree<T> getRight() {
return this.right;
}
}
Change Tree class
static class Tree<T> {
private T value;
private final Tree<T> left;
private final Tree<T> right;
public Tree(T v, Tree<T> l, Tree<T> r) {
this.value = v;
this.left = l;
this.right = r;
}
public T getValue() {
return this.value;
}
// getters ...
}
And also change isOk()
@Override
public boolean isOk(Tree<V> tree) {
return minEle.compareTo(tree.getValue()) <= 0 &&
maxEle.compareTo(tree.getValue()) >= 0;
}