java - 如何将compareTo与T Java泛型一起使用?

标签 java generics heap heapsort

我尝试将compareTo与Java泛型一起使用,但它一直给我一个错误。然后我实现了

public interface Comparable<T> {
    int compareTo(T o);
}

但还是没有帮助。编译器一直建议我使用 私有(private)无效堆_Rebuild(int ar) 这是我的代码:

 private void heap_Rebuild(T[] ar, int root, int size) {

    int child =2*root+1;
    if(child<size){
        int rightChild=child+1;

        if((rightChild<size)&& (ar[rightChild].compareTo(ar[rightChild])>0)){
            child=rightChild;
        }
        if(ar[root].compareTo(ar[child])<0){
            T temp=ar[root];
            ar[root]=ar[child];
            ar[child]=temp;
            heap_Rebuild(ar,child,size);
        }
    }

其余代码:

public class HeapSort<T> implements Function<T, U> {

protected Comparator<T> c;
@SuppressWarnings("unchecked")
public HeapSort() {
    this.c = (e1, e2) -> ((Comparable<T>)e1).compareTo(e2);

}

/** Create a BST with a specified comparator */
public HeapSort(Comparator<T> c) {
    this.c = c;

}

public   void sort(T[] anArray) {
    for(int index = anArray.length-1; index >=0; --index) {
        heapRebuild(anArray,index,anArray.length);

    }
    heapSort(anArray);
}

private void heapSort(T[] anArray) {
    // Left as an exercise

    int arrayLength=anArray.length;
    int index, step;
    for (index = arrayLength-1; index >=0; index--) {
        heapRebuild(anArray,index,arrayLength);
    }

    int last=arrayLength-1;
    for(step=1; step<=arrayLength;step++){
        int temp=last;
        anArray[last]=anArray[0];
        anArray[0]=anArray[temp];
        last--;
        heapRebuild(anArray,0,last);
    }

}

有什么建议吗?

最佳答案

您需要为类型变量T设置一个界限这样该类型的对象保证具有 .compareTo方法。

public class HeapSort<T extends Comparable<? super T>> implements Function<T, U>

听起来你定义了自己的Comparable<T>界面,但是T不相关,泛型类型变量仅适用于定义它的类或方法。您应该删除多余的 Comparable<T>界面。

<小时/>

或者,如果您希望能够对 T 使用不可比较类型,您使用 Comparator<T> 的想法是正确的,但您的默认实现将不起作用:

this.c = (e1, e2) -> ((Comparable<T>)e1).compareTo(e2);

如果T还不是可比较的类型,则强制转换为 Comparable<T>将失败。我建议不要使用默认构造函数并始终传递 Comparator<T> 。当使用可比较的类型时,可以传递 Comparator.naturalOrder() .

您可以使用比较器来替换 compareTo来电:

if((rightChild<size)&& (c.compare(ar[rightChild],ar[rightChild])>0)){

if(c.compare(ar[root],ar[child])<0){

关于java - 如何将compareTo与T Java泛型一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713585/

相关文章:

java - 动态改变嵌套for循环的数量

java - 如何配置我的表达式语言以在 Eclipse 中工作,同时还使用 JSP/JSTL?只是 JSP 吗?

java - Java 中带有空参数的 Varargs

java - 使用 @ManyToMany 反序列化并持久化

java - 为什么 javac 不能为用作参数的函数推断泛型类型参数?

java - 如果已添加项目的值发生变化,如何管理堆(最小堆)

algorithm - 具有相同 key 算法的两个堆

generics - 使用接受闭包的方法在 Rust 中创建对象安全特征

Java如何: Creation of Generic List?

python - python中堆元素的比较顺序