svs*_*sav 3 java tree binary-search-tree
我正在写一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
getValue()的返回类型为Object,因此java.lang.Object类型.这是我第一次见到这个错误.谁能给我一些关于这个错误的背景知识?谢谢
当然 - 你根本无法>在对象之间应用运算符.你期望它做什么?你可以不适用任何其他二元运算符的任何- ,,+ 等(与字符串连接除外).-/
理想情况下,你应该制作你的TreeNode 泛型,并且要么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
}
Run Code Online (Sandbox Code Playgroud)
要么
int comparisonResult = current.getValue().compareTo(t.getValue());
// Code as before
Run Code Online (Sandbox Code Playgroud)
如果没有泛型,你可以将值转换为Comparable或仍然使用一般Comparator...但泛型将是一个更好的选择.