In Java, I wrote a Binary Search Tree class that adds nodes using recursion. Now I want to generalize it using Generics so I can learn more about them.
public class GBinNode<T> {
T item;
GBinNode<T> left;
GBinNode<T> right;
public GBinNode(T newItem) {
item = newItem;
left = null;
right = null;
}
public GBinNode(T it, GBinNode<T> le, GBinNode<T> ri) {
item = it;
left = le;
right = ri;
}
public String toString() {
return item.toString()+" ";
}
}
My function to add nodes is in the following class
public class GBinTree<T extends Comparable <T>> {
GBinNode<T> add(T item, GBinNode<T> bn) {
if (bn==null) {
return new GBinNode<T>(item, null, null);
}
if (item < bn.item) { // ERROR HERE
bn.left = add( item, bn.left);
}
else {
bn.right = add( item, bn.right);
}
return bn;
}
public void toString(GBinNode<T> root) {
GBinNode<T> curr = root;
if (curr == null)
return;
else {
toString(curr.left);
System.out.println(curr.toString()); // inorder traversal
toString(curr.right);
}
}
The main class has the following code to kick things off. I'm using strings, but the data type could be some complex type.
GBinTree<String> bt = new GBinTree<String>();
GBinNode<String> root = null;
root = bt.add("Calex", root);
root = bt.add("Ealex", root);
root = bt.add("Balex", root);
root = bt.add("Dalex", root);
bt.toString(root);
I started to use the Comparable interface but then how do I write the CompareTo() function? I don't know what type T will be? The error I got was "The operator < is undefined for the argument type(s) T, T".
Searching for a solution, one answer was Comparing generic types Java:
class Element<T extends Comparable<T>>
I don't understand where this should go, and how it's different from the class implementing Comparable. The only place I know the type is in the main class, so should the compareTo() be there? I looked at making GBinTree an interface, but got confused whether that was the right track? Any help would be appreciated.