二元运算符的错误操作数类型“>”?
我正在写一个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类型。 这是我第一次见到这个错误。 谁能给我一些关于这个错误的背景知识? 谢谢
当然 – 你根本无法在对象之间应用>
运算符。 你期望它做什么? 您不能应用任何其他二元运算符 – +
, -
, /
etc(字符串连接除外)。
理想情况下,您应该使TreeNode
通用性 ,并且要么具有能够比较任何两个实例的Comparator
,要么使T extend Comparable
。 无论哪种方式,您都可以将它们与:
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
如果没有generics,你可以将值转换为Comparable
或者仍然使用一般的Comparator
......但是generics将是一个更好的选择。
Java不支持运算符重载,因此没有为非基本类型定义<
运算符。 您可能希望使用Comparable
接口。
您无法使用>
或<
来比较对象。 您需要使用某种方法比较它们,例如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。
- 线程“main”中的exceptionjava.lang.NoClassDefFoundError:org / codehaus / jackson / JsonParseException
- 了解Android中的AudioTrack断言