Java Generic Casting Type Mismatch

Posted by Kay on Stack Overflow See other posts from Stack Overflow or by Kay
Published on 2010-04-15T19:33:36Z Indexed on 2010/04/15 19:43 UTC
Read the original article Hit count: 346

Filed under:
|
|
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
}

}

The error is on the line with "T[arr] = {1,3,4,5,2}"

Eclispe complains that there is a:

"Type mismatch: cannot convert from int to T"

I've tried to casting nearly everywhere but to no avail.A simple way out would be to not use generics but instead just ints but that's sadly not an option. I've got to find a way to resolve the array of ints "{1,3,4,5,2}" into an array of T so that the rest of my code will work smoothly.

© Stack Overflow or respective owner

Related posts about java

Related posts about generics