我在我的主类
中创建了一个ObjectSearchTreeInterface < MyClass > object = new BinarySearchTree <MyClass> ();
我收到了这个错误:
Bound mismatch: The type MyClass is not a valid substitute for the bounded parameter <T extends Comparable<? super T>> of the type SearchTreeInterface<T>
我记得在我以相同的方式使用Array List之前我有这个错误
我的修复是通过添加new Comparable
来改变我的构造函数中的声明。像这样:
public ArrayList(int size){
@SuppressWarnings("unchecked")
T[] temp = (T[]) new Comparable[size];
list=temp;
numberOfEntries = 0;
}
我如何为BinarySearchTree构造函数执行相同的操作?
这就是他们目前的样子:
public BinarySearchTree ()
{
super ();
} // end default constructor
public BinarySearchTree (T rootEntry)
{
super ();
setRootNode (new BinaryNode < T > (rootEntry));
} // end constructor
我应该在哪里以及如何向此添加new Comparable
?谢谢!
答案 0 :(得分:0)
您的MyClass
需要延长Comparable
,因此它应如下所示:
public class MyClass extends Comparable<MyClass> {}
(Comparable
允许在列表内对类进行排序等)
你还需要添加一个函数int compareTo(T o) {}
,它返回:
-1 if the current instance should be listed before o
0 if the current instance equals o
1 if the current instance should be listed after o
(您可能需要切换-1&amp; 1,而不是100%确定:)