BinarySearchTree 的构造函数<T 扩展了 Comparable<? Super T>>以避免绑定不匹配错误?



我在我的主流中创建一个对象

SearchTreeInterface < 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>

我记得我在使用数组列表相同的方式和
时遇到了这个错误我的修复是通过添加new Comparable来更改约束者中的声明:

public ArrayList(int size){
    @SuppressWarnings("unchecked")  
    T[] temp = (T[]) new Comparable[size];
    list=temp;
    numberOfEntries = 0;
}

我该如何为我的二进制搜索构建器做同样的事情?

这就是他们当前的样子:

 public BinarySearchTree ()
{
    super ();
} // end default constructor

public BinarySearchTree (T rootEntry)
{
    super ();
    setRootNode (new BinaryNode < T > (rootEntry));
} // end constructor

在哪里以及如何将new Comparable添加到此?谢谢!

您的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%确定:)

最新更新