I am attempting to implement a Binary Search Tree as an assignment. We are experiencing resolving issues of derivation, inheritance, etc, so the tree can potentially hold data of a variety of different types.
In past assignments I had used base class pointers as the data type, and utilized RTTI/upcasting/downcasting to access data, I read that this is inefficient and bad practice, so I'm trying to move away from it.
To that end, I'm trying to implement a generic node/tree structure, but am having a couple of issues. First, when it comes to calling a "display" method from a generic data member, is that even possible? Since the node may not know what type of data is being stored, or if the method even exists to be called?
Second, when trying to cast an object to I get an unchecked cast exception, is there a way to resolve this? Or conduct a checked cast?
Any advice or helpful solutions would be appreciated.
EDIT: Here is some code... BSTNode implementation:
/**
* Class declaration for a BST Node. Holds left and right pointers, and a data
* member. Contains methods for getting/setting left, right, and data.
*/
public class BSTNode<T extends Comparable<T>> {
private BSTNode<T> left, right, next; //ptr for left/right/next nodes.
private T data; //Integer for data.
public BSTNode(){
left = right = next = null; //Set left/right/next ptrs to NULL.
}
public BSTNode(T n){
left = right = next = null; //Sets left/right/next ptr to NULL.
this.data = n; //Init data to passed in arg.
}
public BSTNode<T> getLeft() {return this.left;}
public BSTNode<T> getRight() {return this.right;}
public BSTNode<T> getNext() {return this.next;}
public T getData() {return this.data;}
public void setLeft(BSTNode<T> left) {this.left = left;}
public void setRight(BSTNode<T> right) {this.right = right;}
public void setNext(BSTNode<T> n) {this.next = n;}
public void setData(T d) {this.data = d;}
}
Insertion:
public class Interface<T extends Comparable<T>> extends Utility {
...
case 1:
Subjob sub1 = new Subjob("Test");
BSTNode<T> temp = new BSTNode<T>(sub1); //ERROR ON THIS LINE
exit = true;
return 1;
Sounds like an interface should be used as the basis for the BST. The interface would need to be comparable (as required by the BST) and provided the method display(). Then it is up to implementations to provide that method properly.
The interface might look like:
public interface Displayable<T> extends Comparable<T> {
void display();
}
Internally to the BST, it might have a node as follows:
public class Node<T> {
Displayable<T> value;
Node<T> left;
Node<T> right;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments