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}“
Eclipse 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.
When you use a generic type, you must resolve all the type parameters, i.e. tell the compiler which concrete types you want to use instead of the placeholder
Tin your code. As the others already pointed out, a primitive type likeintcan’t be used as a generic type parameter – it must be a reference type, likeInteger. So you can rewrite yourmainmethod into something likeNote that it should be
static. When you instantiate your class, you have to specify the type parameterIntegeras above. Then you can pass it the array to be sorted.A further note: this loop
will never execute – the loop condition should be
i > 0instead.