-1

I'm trying to implement a Binary Search Tree, just for the sake of learning, and I want the tree to be generic. This is the code I have so far (very limited):

package lect1;

public class BinNode {
    Comparable element;
    BinNode left;
    BinNode right;

    public BinNode find(Comparable obj) {
        if (element == null) {
            return null;
        } else if (obj.compareTo(left.element) < 0) {
            left.find(obj);
        } else if(obj.compareTo(right.element) > 0) {
            right.find(obj);
        } else {
            return this;
        }
        return null;
    }

    public void insert(Comparable obj) {

    }
}

However, I get the error message Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'. Could any of you shed some light as to how I would solve this.

Arash Saidi
  • 2,228
  • 20
  • 36

1 Answers1

1

Comparable<T> is a generic type, but you're using the raw type, losing type safety. You probably want to make your BinNode generic too, in its element type:

public class BinNode<T extends Comparable<T>> {
    private T element;
    private BinNode<T> left;
    private BinNode<T> right;

    public BinNode<T> find(T obj) {
        // TODO: Handle the cases where left or right is null
        if (element == null) {
            return null;
        } else if (obj.compareTo(left.element) < 0) {
            return left.find(obj);
        } else if (obj.compareTo(right.element) > 0) {
            return right.find(obj);
        } else {
            return this;
        }
    }

    public void insert(T obj) {

    }
}

The constraint on T then ensures that elements will be comparable with each other.

Note that I've also fixed your recursion - previously you were calling left.find() or right.find() but ignoring the return value.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194