Java 二进制运算符“的操作数类型错误”&燃气轮机&引用;?
我正在写一个BST程序。我得到一个错误: “二进制运算符的操作数类型错误”>“ 第一种类型:java.lang.Object 第二种类型:java.lang.Object“ 这是给我错误信息的方法:Java 二进制运算符“的操作数类型错误”&燃气轮机&引用;?,java,tree,binary-search-tree,Java,Tree,Binary Search Tree,我正在写一个BST程序。我得到一个错误: “二进制运算符的操作数类型错误”>“ 第一种类型:java.lang.Object 第二种类型:java.lang.Object“ 这是给我错误信息的方法: public void placeNodeInTree(TreeNode current, TreeNode t) { if(current == n
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);
}
}
public void placeNodeInTree(TreeNode current,TreeNode t)
{
如果(当前==null)
电流=t;
否则{
if(current.getValue()>t.getValue())
当前设置权限(t);
if(current.getValue()
getValue()的返回类型为Object,因此为java.lang.Object类型。这是我第一次看到这个错误。有人能给我一些关于这个错误的背景资料吗?谢谢当然-您不能在对象之间应用
操作符。你希望它做什么?不能应用任何其他二进制运算符-+
、-
、/
等(字符串连接除外)
理想情况下,您应该使您的TreeNode
通用,或者使用能够比较任意两个实例的比较器
,或者使T extend可比较
。无论哪种方式,您都可以将其与以下内容进行比较:
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
}
如果没有泛型,您可以将值强制转换为
Comparable
,或者仍然使用常规比较器
。。。但是泛型是更好的选择。您无法使用
或比较对象Java不支持运算符重载,因此您无法使用
运算符比较两个仲裁对象。
运算符只能(直接)用于基本整数类型
您可以使要比较的对象实现接口java.lang.Compariable
,然后对它们调用Comparieto
方法进行比较
Comparable left = (Comparable)current.getValue();
Comparable right = (Comparable)t.getValue();
if (left.compareTo(right) > 0)
current.setRight(t);
// etc.
equals的默认实现只关心引用相等。一个物体不知道猫是否比苹果大,也不会在意。您应该提供一个覆盖equals和hashcode的具体实现,并实现可比较的接口。这将允许您确定Cat是否比Apple更强大。我认为您可以使用另一个基本变量,如
int temp=(int)current.getValue();
有没有其他方法可以做到这一点?您确定这些对象只有“对象”父对象的共同点吗?如果是这样,就没有真正的比较了。尝试找到类的真实类型(例如使用instanceof),然后尝试进行比较。或者尝试重构getValue(),以确保它返回使用或使用的内容。是否可以将.Canjava.lang.Object
强制转换到int
?欢迎使用堆栈溢出!这似乎没有回答关于使用
int temp=(int)current.getValue();