Search code examples
javagenericscomparecomparable

Comparing Generics that are comparable in Java


I have a Generic Binary Tree that will add objects lessThan or equalTo to the left, and objects greater than to the right. My problem is with the comparing the Generics, I know the data value will be a object-wrapped primitive or a String, so they are comparable. But, I do not know how to implement this in the code.

The code is a work in progress, I know the add methods don't add correctly yet, but I am working on that. Thanks

Here is the TreeNode:

public class TreeNode<T>
{
    //Instance Variables
    TreeNode leftChild;
    TreeNode rightChild;
    int childCount;
    int depth;
    T data;


    public TreeNode(T data, int parentDepth)
    {
        leftChild = null;
        rightChild = null;
        childCount = 0;
        depth = parentDepth + 1;
        this.data = data;
    }

    public TreeNode(int parentDepth)
    {
        leftChild = null;
        rightChild = null;
        childCount = 0;
        depth = parentDepth + 1;
        data = null;
    }


    public void add(T data)
    {
        if (this.data.compareTo(data) <= 0)
        {
            addLeft(data);
        } else if (this.data.compareTo(data) > 0)
        {
            addRight(data);
        } else
        {
            System.out.println("ERROR IN TREENODE.ADD");
        }
    }


    public void addLeft(T data)
    {
        leftChild = new TreeNode(data, depth);
    }

    public void addLeft()
    {
        leftChild = new TreeNode(depth);
    }


    public void addRight(T data)
    {
        rightChild = new TreeNode(data, depth);
    }

    public void addRight() {
        rightChild = new TreeNode(depth);
    }
}

Solution

  • I know the data value will be a object-wrapped primitive or a String, so they are comparable.

    Then you can tell the compiler about it:

    public class TreeNode<T extends Comparable<T>>
    

    If you do that, you will get access to the compareTo method defined in Comparable.