2

How can I do the test without error?

Because of that object can not be used in this operator?

i have error(in insert function) why?

The error:

The operator < is undefined for the argument type(s) java.lang.Object, java.lang.Object

public class BinarySearchNode {
protected Object data;

protected BinarySearchNode left;
protected BinarySearchNode right;

public BinarySearchNode(Object data) {
    if (data == null)
        throw new RuntimeException("we are too lazy to deal with null data");

    this.data = data;
    this.left = null;
    this.right = null;
}

public void insert(Object toAdd) {
    if **(toAdd < data)** { <<<<<<<<<<<<<<<<<<< here 
        if (left == null)
            left = new BinarySearchNode(toAdd);
        else
            left.insert(toAdd);
    } else {
        if (right == null)
            right = new BinarySearchNode(toAdd);
        else
            right.insert(toAdd);

    }
}

public void InOrderPrint() {
    if (left != null)
        left.InOrderPrint();

    System.out.println(this.data);

    if (right != null)
        right.InOrderPrint();

}
 }

2 Answers 2

1

You have two approaches to establishing an order of Objects:

  • Replace Object with Comparable<T> - this would let you put the comparison logic into the object itself, or
  • Ask the caller to supply an implementation of Comparator<T> - this would let your callers supply the logic directly when using your APIs.

Here is how you would use the first approach:

public class BinarySearchNode<T extends Comparable<T>> {
    protected T data;
    ...
    public void insert(T toAdd) {
        if (toAdd.compareTo(data) < 0) {
            ...
        } else {
            ...
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

The < (less then) operator is a relational operator and it works only with numerical values. It can work with the objects derived from java.lang.Number, but before to perform the comparison, the compiler "makes" an automatic unboxing operation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.