java - 如何将 compareTo 与 T Java 泛型一起使用?
问题描述
我正在尝试将 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);
}
}
有什么建议么?
解决方案
您需要为类型变量设置一个界限,T
以便保证该类型的对象具有该.compareTo
方法。
public class HeapSort<T extends Comparable<? super T>> implements Function<T, U>
听起来您定义了自己的Comparable<T>
接口,但这T
无关紧要,泛型类型变量仅适用于定义它的类或方法。您应该删除那个额外的Comparable<T>
接口。
或者,如果您希望能够对 使用不可比较的类型T
,那么您使用 a 的想法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){
推荐阅读
- python - 在 Python 字典中查找最接近的值并返回其键
- jquery - 发送请求后触发 jQuery ajaxPrefilter
- hadoop - Hive Beeline 输出 ^M 和空字符
- typescript - 如何在 TypeScript 中为特定类型的泛型类型创建扩展方法
- python - 如何删除除 1 个特定小部件以外的所有子项?
- java - Javassist ; 引起:编译错误:没有这样的类:记录器
- javascript - 如何在 Electron BrowserWindow 中查看 PDF?
- ruby-on-rails - 如何在 ActionMailer 中将云文件添加为电子邮件附件
- php - 获取自定义支付网关数据作为 Woocommerce 3 中的设置
- go - 使用 gocql 将用户定义类型的数组插入 Cassandra