Reputation: 61
TreeComparable
is a Comparable
interface.
The Error:
java.lang.String cannot be cast to TreeComparable
This is the line giving me the error
if (((TreeComparable) r.getInfo()).compareTo((TreeComparable) p.getInfo()) < 0 )
And here is the method for that line:
public void insertBST(Object o) {
ObjectTreeNode p, q;
ObjectTreeNode r = new ObjectTreeNode(o);
if (root == null)
root = r;
else {
p = root;
q = root;
while (q != null) {
p = q;
if (((TreeComparable)(r.getInfo())).compareTo((TreeComparable)(p.getInfo())) < 0 )
q = p.getLeft();
else
q = p.getRight();
}
if (((TreeComparable)(r.getInfo())).compareTo((TreeComparable)(p.getInfo())) < 0)
setLeftChild(p, r);
else
setRightChild(p, r);
}
}
Note: BST stands for binary search tree.
The getInfo
method of the ObjectTreeNode
class:
private Object info;
public Object getInfo() {
return info;
}
and finally, I don't know if these will help, but my TreeComparable
compareTo
declaration:
int compareTo(Object o);
and the compareTo
method in the (Word)
class:
String word;
public int compareTo(Object o) {
Word w = (Word) o;
return this.word.compareTo(w.getWord());
}
The Help is greatly appreciated.
Upvotes: 0
Views: 207
Reputation: 23965
This is because String
does not implement the interface TreeComparable
. There is a an interface Comparable
that String
implements. String can be upcasted to this interface.
Upvotes: 1