java 二元运算符 '&&' 的操作数类型错误,二元运算符的错误操作数类型“>”?...

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

解决方案

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 which is able to compare any two instances, or make T extend Comparable. 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值