二元运算符的错误操作数类型“>”? [英] Bad Operand Types for Binary Operator ">"?
问题描述
我正在写一个BST计划。我收到错误:
I am writing a BST Program. I get the error:
二元运算符的错误操作数类型>
"Bad Operand Types for Binary Operator ">"
第一种类型:java。 lang.Object
first type: java.lang.Object
第二种类型: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()的返回类型为Object,因此java.lang.Object类型。这是我第一次见到这个错误。谁能给我一些关于这个错误的背景知识?谢谢
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
推荐答案
当然 - 您根本无法应用>
对象之间的运算符你期望它做什么?您不能应用任何其他二元运算符 - +
, -
, /
etc(字符串连接除外)。
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).
理想情况下,你应该使你的 TreeNode
泛型,并且要么有一个 Comparator< T>
,它能够比较任何两个实例,或者生成 T extend Comparable< T>
。无论哪种方式,您都可以将它们与以下内容进行比较:
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
}
或
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.
这篇关于二元运算符的错误操作数类型“>”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!