Reputation: 1275
I want to create a tree that detect if the insert is a Object of type Characters it will compare each one and decide where to insert [ right or left ],( i know it can detect by position in ascii table) ,and if the insert is an object of int it will do the same operation.
My Questions:
1. I need to create the tree and on the same time to set a compartor ( for example if its a tree of Chars it will be a Chars_comperator that checks Chars and he implements Comparator ( of java ).?
2. My code now is good for int only. becuase i take the object convert to string and then to int and after all this i compare and decide where to insert, this is how i need to do it? or there is another way to do it that can take care all of kinds of Objects?
Here is my code and how i create the tree,
Tree class
public class tree {
bNode root;
public tree() {
this.root = null;
}
public boolean isEmpty(){
return root==null;
}
public void insert(Object data)
{
if(isEmpty())
this.root = new bNode(data);
else
this.root.insert(data);
}
}
bNode Class
public class bNode {
protected Object data;
protected bNode left;
protected bNode right;
public bNode(Object data) {
this.data = data;
this.left = null;
this.right = null;
}
public void insert(Object data){
if(Integer.parseInt(data.toString())<Integer.parseInt(this.data.toString())){
if(this.left==null)
this.left = new bNode(data);
else
this.left.insert(data);
}
else{
if(this.right==null)
this.right = new bNode(data);
else
this.right.insert(data);
}
}
Main class
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
tree x = new tree();
char a = 'G';
x.insert(a);
x.insert(60);
x.insert(40);
x.insert(30);
x.insert(59);
x.insert(61);
x.root.printTree(x.root);
}
}
Thanks!
Upvotes: 0
Views: 167
Reputation: 196
instead of passing an Object, you could pass a Comparable
in insert()
.
Standard type like Integer, String, etc. already implement the Conparable interface.
instead of using if (a <b
) you call
compareTo(a,b);
See java doc of Comparable.
If, for any reason, you want to stay with Passing an Object
to insert()
, you also can solve that by not using toString, but by checking the class of object, and then casting:
if (object instanceof Integer) {
int val = ((Integer) object).intValue();
// now compare
} else if (object instance of String) {
String val .....
// use val.compareTo()
}
Upvotes: 1