I think what you are trying to do is create a new collection. If this is for learning purpose, then you could just define your BST as:
class BST<E implements Comparable<E>>{
private Node root;
//...
private class Node{ // instances of Node are bound to the instance of BST
E elem;
Node left, right;
}
}
or with a static inner class:
class BST<E implements Comparable<E>>{
private Node<E> root;
// ...
private static class Node<X implements Comparable<X>>{
// similar
}
}
Note that it's good practice to have your Node
class defined as an inner class and make it either private or with a private constructor. This ensures encapsulation of the implementation.
I want to point out that this is not the approach taken in the SDK. In the library, it's always possible to create a data structure by passing an appropriate Comparator<E>
so that no natural ordering is required or can be overwritten. If you want to follow this other approach look at the implementation of TreeSet
or something like that. You can either pass the Comparator
or the type in the collection will be checked at run time to implement Comparable
. This has the advantage of being more flexible because you can add to the collection objects for which you cannot change the implementation.
Finally, if you need to implement a collection for a project or work, then don't. The SDK has plenty of collections and there are also the Guava collections.