我尝试将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/