我正在编写一个 BST 程序。我收到错误:
“二元运算符的错误操作数类型">”
第一种类型:java.lang.Object
第二种类型:java.lang.Object”
这是给我错误的方法:
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 类型。这是我第一次看到这个错误。谁能给我一些有关此错误的背景信息?谢谢
当然 - 您根本无法在对象之间应用
>
运算符。您希望它做什么?您也不能应用任何其他二元运算符 - +
、-
、/
等(字符串连接除外)。
理想情况下,您应该制作
TreeNode
generic,并且要么有一个能够比较任意两个实例的 Comparator<T>
,要么制作 T extend Comparable<T>
。无论哪种方式,您都可以将它们与:
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
如果没有泛型,您可以将值转换为
Comparable
或仍然使用通用Comparator
...但泛型将是更好的选择。
Java 不支持运算符重载,因此没有为非基本类型定义
<
运算符。您可能想改用 Comparable<T>
界面。
您无法使用
>
或 <
来比较对象。您需要使用某种方法来比较它们,例如compareTo(您需要实现)。
您无法使用
>
运算符比较两个仲裁对象。 >
运算符只能(直接)用于原始整数类型。
你可以让你想要比较的对象实现接口
java.lang.Comparable
,然后调用它们的compareTo
方法来比较它们。
Comparable left = (Comparable)current.getValue();
Comparable right = (Comparable)t.getValue();
if (left.compareTo(right) > 0)
current.setRight(t);
// etc.
equals 的默认实现只关心引用相等性。 对象不知道 Cat 是否大于 Apple,也不会关心。 您应该提供一个覆盖 equals 和 hashcode 并实现 Comparable 接口的具体实现。 这将使您能够确定 Cat 是否确实比 Apple 更伟大。
我认为你可以使用另一个原始变量,例如
int temp=(int)current.getValue();
我刚刚遇到了这个错误。解决方案是我忘记了我正在迭代 ArrayList 来访问对象,并且需要使用点表示法来访问我想要使用的方法。我将这个对象视为主要对象。