比较已实现可比较的类的对象

时间:2014-07-19 11:10:03

标签: java compare

我正在学习二叉搜索树并尝试用Java实现它。

    public class BinarySearchTree<T>
    {
        private class Node
        {
            public T data;
            public Node left;
            public Node right;
        }

        //some code goes here

        public void insert(T data)
        {
            //make a new node and add data to that node
            //call to recursive function
        }
        private Node ins(Node root,Node toBeInserted)
        {
            if(root==null) { root = tobeInserted; return root; }

            //problem is here...
            else if(toBeInserted.data<=root.data)// <----How to do this ?????
                root = ins(root.left,toBeInserted);
            else
                root = ins(root.right,toBeInserted);
            return root;
        }
        //some more code
    }

问题是如何比较T类的对象? 如果我在某个类T中实现了可比性,那么如何比较存储在左右节点中的数据???

提前致谢。

2 个答案:

答案 0 :(得分:2)

如果T始终实现Comparable,您可以在其定义中添加适当的绑定:

public class BinarySearchTree<T extends Comparable<T>> { ... }

然后您可以使用compareTo()

toBeInserted.data.compareTo(root.data) <= 0

答案 1 :(得分:0)

将类定义设为

public class BinarySearchTree<T extends Comparable<T>>

然后插入

试试这个

  /**
  * This method inserts new node in tree
  * @param value
  */
 public void insert(T value){
  if(isEmpty())
   root = new Node(value);  //root node added
  else
   insert(root, value);  //if not empty then insert based on root
 }

 /**
  * Recursive method is called internally to insert nodes at proper 
    places depending on their vakues.
  * @param node
  * @param value
  */
 private void insert(Node node, T value){
  if(value.compareTo(node.value) < 0){  //if new value less than parent node
   if(node.left == null)  //if left null then add
    node.left = new Node(value);
   else
    insert(node.left,value);  //if left not null then recursive call
  }
  else if(value.compareTo(node.value) >= 0){  //if new value same or greater than parent node
   if(node.right == null)  //if right null then add
    node.right = new Node(value);
   else
    insert(node.right,value);  //if right not null then recursive call
  }
 }

访问链接here以获取完整的源代码。

相关问题