Java Generic Casting Type Mismatch

时间:2010-04-15 19:33:36

标签: java generics casting

public class MaxHeap<T extends Comparable<T>> implements Heap<T>{
private T[] heap;
private int lastIndex;

public void main(String[] args){
    int i;
    T[] arr = {1,3,4,5,2}; //ERROR HERE *******
    foo
}

public T[] Heapsort(T[]anArray, int n){
    // build initial heap
    T[]sortedArray = anArray;
    for (int i = n-1; i< 0; i--){
        //assert: the tree rooted at index is a semiheap
        heapRebuild(anArray, i, n);
        //assert: the tree rooted at index is a heap
    }
    //sort the heap array
    int last = n-1;
    //invariant: Array[0..last] is a heap,
    //Array[last+1..n-1] is sorted
    for (int j=1; j<n-1;j++) {
        sortedArray[0]=sortedArray[last];
        last--;
        heapRebuild(anArray, 0, last);
    }
    return sortedArray;
}

protected void heapRebuild(T[ ] items, int root, int size){
foo
}

}

错误在“T[arr] = {1,3,4,5,2}

的行上

Eclipse抱怨说有一个:

  

“类型不匹配:无法转换   int到T“

我试图在几乎所有地方投射,但无济于事。一个简单的方法是不使用泛型,而只是内联,但遗憾的是这不是一个选择。我必须找到一种方法将整数{1,3,4,5,2}数组解析为T数组,以便我的其余代码能够顺利运行。

4 个答案:

答案 0 :(得分:1)

arr声明为Integer[]而不是T[]。我在这里修复了一些其他的小错误:

public static void main(String[] args){
    int i;
    Integer[] arr = {1,3,4,5,2}; //ERROR HERE *******

}

public <T> T[] Heapsort(T[]anArray, int n){
    // build initial heap
    T[]sortedArray = anArray;
    for (int i = n-1; i< 0; i--){
        //assert: the tree rooted at index is a semiheap
        heapRebuild(anArray, i, n);
        //assert: the tree rooted at index is a heap
    }
    //sort the heap array
    int last = n-1;
    //invariant: Array[0..last] is a heap,
    //Array[last+1..n-1] is sorted
    for (int j=1; j<n-1;j++) {
        sortedArray[0]=sortedArray[last];
        last--;
        heapRebuild(anArray, 0, last);
    }
    return sortedArray;
}

protected void heapRebuild(T[ ] items, int root, int size){
   //foo
}

答案 1 :(得分:1)

使用泛型类型时,必须解析所有类型参数,即告诉编译器要使用哪些具体类型而不是代码中的占位符T。正如其他人已经指出的那样,像int这样的基本类型不能用作泛型类型参数 - 它必须是引用类型,如Integer。因此,您可以将main方法重写为类似

的方法
public static void main(String[] args){
    int i = 5;
    Integer[] arr = {1,3,4,5,2};
    MaxHeap<Integer> maxHeap = new MaxHeap<Integer>();

    maxHeap.heapSort(arr, i);
}

请注意,它应为static。实例化类时,必须如上所述指定类型参数Integer。然后你可以将它传递给要排序的数组。

进一步说明:此循环

for (int i = n-1; i< 0; i--){
    ...
}

永远不会执行 - 循环条件应该是i > 0

答案 2 :(得分:0)

嗯,曾经想过如果你在MaxHeap中运行这个代码会发生什么,比方说,String对象?

在实际实例化泛型类之前,T不存在。因此,如果你不知道T是什么,用整数创建一个T数组是没有意义的。

编辑:此外,Java中的泛型仅适用于引用类型,而int是值类型。尝试使用Integer(int的包装类)。

答案 3 :(得分:0)

你已经说过T extends Comparable<T>了。 “int”不会延伸Comparable<T>,无论你如何施展它。

相关问题