二元运算符“>"的错误操作数类型? [英] Bad Operand Types for Binary Operator ">"?

查看:31
本文介绍了二元运算符“>"的错误操作数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 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

推荐答案

当然 - 您根本无法在对象之间应用 > 运算符.你希望它做什么?您也不能应用任何其他二元运算符 - +-/ 等(字符串连接除外).

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 generic,或者有一个 Comparator 能够比较任意两个实例,或使 T 扩展 Comparable.无论哪种方式,您都可以将它们与以下内容进行比较:

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

如果没有泛型,您可以将值转换为 Comparable 或仍然使用通用的 Comparator...但泛型会更好.

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

这篇关于二元运算符“>"的错误操作数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆