Reputation: 3
First time posting. Having trouble finding an answer, so here goes:
Introduction: It's part of my homework. Assignment was to work on integer binary tree. First 3 steps were about programming a dozen methods to manipulate and play around with the tree like adding new nodes, counting, traversing, summing, etc. 4th part required creating the exact same class only for strings, where values would be compared using compareTo method.
Problem: Next step of the assignment requires using polymorphism to allow nodes to accept either int or string. Since I was only briefly introduced to this on our last lecture, I have found myself stuck for past few hours looking for solution, unsuccessfully.
Code:
public class Node<T extends Comparable<T>> {
T val;
Node<T> left, right;
public Node(T val) {
this.val = val;
this.left = null;
this.right = null;
}
public Node<T> insert(Node n, T v) {
if (n == null) {
return new Node(v);
}
if (v.compareTo(n.val) == 0) {
return n;
}
if (v.compareTo(n.val) < 0) {
n.left = insert(n.left, v);
} else {
n.right = insert(n.right, v);
}
return n;
}
...
}
The problem is using compareTo()
on Raw types. I can't find anywhere how would I go about comparing two objects/raw types. I have tried numerous variations usually all with similar results. The debugger is constantly reminding me "incompatible types: Comparable cannot be converted to T". How exactly would I have to implement Comparable for this binary tree to work?
Upvotes: 0
Views: 557
Reputation: 106400
It seems that it's as simple as parameterizing your Node
passed in.
public Node<T> insert(Node<T> n, T v)
Another solution to that would be to have Node
itself implement Comparable
.
public class Node<T extends Comparable<T>> implements Comparable<Node<T>> {
// ...
}
Upvotes: 1