Bad Operand Types for Binary Operator “>”?

2019-01-20 00:37发布

问题:

I am writing a BST Program. I get the error:

"Bad Operand Types for Binary Operator ">"

first type: java.lang.Object

second type: java.lang.Object"

This is the method where it gives me the error:

public void placeNodeInTree(TreeNode current, TreeNode t)                                                                    
{   
    if(current == null)
        current = t;
    else{
       if(current.getValue() > t.getValue()) 
            current.setRight(t);
       if(current.getValue() < t.getValue()) 
            current.setLeft(t);  
        }
}

getValue() has a return type of Object, thus the java.lang.Object types. This is the first time I have ever seen this error. Can anyone give me some background on this error? Thanks

回答1:

Sure - you simply can't apply the > operator between objects. What would you expect it to do? You can't apply any of the other binary operators either - +, -, / etc (with the exception of string concatenation).

Ideally, you should make your TreeNode generic, and either have a Comparator<T> which is able to compare any two instances, or make T extend Comparable<T>. Either way, you can then compare them with:

int comparisonResult = comparator.compare(current.getValue(), t.getValue());
if (comparisonResult > 0) {
  // current "greater than" t
} else if (comparisonResult < 0) {
  // current "less than" t
} else {
  // Equal
}

or

int comparisonResult = current.getValue().compareTo(t.getValue());
// Code as before

Without generics you could cast the values to Comparable or still use a general Comparator... but generics would be a better bet.



回答2:

Java doesn't support operator overloading, so the < operator is not defined for non-primitive types. You probably want to use the Comparable<T> interface instead.



回答3:

You cannot compare objects using > or <. You need to compare them using some method, like compareTo (which you need to implement).



回答4:

You cannot compare two arbitraty objects with the > operator. The > operator can only be used (directly) on primitive integer types.

You could make the objects you intend to compare implement interface java.lang.Comparable, and then call the compareTo method on them to compare them.

Comparable left = (Comparable)current.getValue();
Comparable right = (Comparable)t.getValue();

if (left.compareTo(right) > 0)
    current.setRight(t);

// etc.


回答5:

The default implementation of equals only cares about reference equality. An object does not know if Cat is greater than Apple nor would it care. You should provide a concrete implementation that overrides both equals and hashcode as well as implements the Comparable interface. This will allow you to determine if in fact Cat is greater than Apple.