如何将compareTo与T Java generic一起使用?

问题描述 投票:1回答:1

我试图使用compareTo与Java泛型,但它一直给我一个错误。然后我实施了

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

但仍然没有帮助。编译器一直建议我使用private void heap_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);
    }

}

有什么建议?

java generics heap heapsort
1个回答
2
投票

您需要为类型变量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){
© www.soinside.com 2019 - 2024. All rights reserved.