我尝试用泛型实现binarysearchtree(add方法),但它给了我这样的错误:
genericstree.java:36: error: bad operand types for binary operator '>'
if ( value > iterator.m_Value )
^
first type: T
second type: T
where T is a type-variable:
T extends Comparable<T> declared in class BinarySearchTree
genericstree.java:42: error: bad operand types for binary operator '<'
if ( value < prev.m_Value )
^
first type: T
second type: T
where T is a type-variable:
T extends Comparable<T> declared in class BinarySearchTree
2 errors
代码如下:
class BinarySearchTree<T extends Comparable<T>>
{
class Node<T extends Comparable<T>>
{
Node<T> left;
Node<T> right;
T m_Value;
Node( T value )
{
left = null;
right = null;
m_Value = value;
}
}
Node<T> m_Root;
BinarySearchTree() { m_Root = null; }
void addNode( T value )
{
Node<T> tmp = new Node<T>( value );
if ( m_Root == null )
{
tmp.m_Value = value;
m_Root = tmp;
return;
}
Node<T> iterator = m_Root;
Node<T> prev = m_Root;
while ( iterator != null )
{
prev = iterator;
if ( value > iterator.m_Value )
iterator = iterator.right;
else
iterator = iterator.left;
}
if ( value < prev.m_Value )
prev.left = tmp;
else
prev.right = tmp;
}
}
我认为问题是被替换的T对象可以通过任何类型然后它无法比较它们但是我用Comparable扩展了类但它没有修复它。
导致问题的原因是什么?如何解决?