I have the following code:
public abstract class Heap {
Comparable<?> data[];
int count, size;
public Heap( int size ) {
this.size = size;
data = new Comparable<?>[ size + 1 ];
this.count = 0;
}
public abstract void insert( Comparable<?> item );
}
class MinHeap extends Heap {
public MinHeap (int size ) { super(size); }
public void insert( Comparable<?> item ) {
//this line here is giving me an error
//due to how I am storing the array in Heap
int k = data[ 0 ].compareTo( item );
}
}
The line indicated above is giving me this error: The method compareTo(capture#1-of ?) in the type Comparable<capture#1-of ?> is not applicable for the arguments (Comparable<capture#2-of ?>)
. I cannot figure out a way to make it work while maintaining these conditions: 1) I want the MinHeap to work with any data that implements Comparable
, 2) I do NOT want to pass a pre-initialized array into the constructor. I say this because I do not want to do the following:
abstract class Heap< T extends Comparable<T> > {
T data[];
public Heap( T data[], int size ) {
this.data = data;
//I do not want to have to pass an instantiated array.
//I want the constructor to handle the instantiation. If I do this I know the issue with the
//compareTo will be solved, but I really prefer to avoid this.
}
}
My question is this: In my code, why am I getting this error? Does anyone know a way besides the way that is described in the second example? I would like to be able to create a min heap data structure with any comparable data. All helpful comments are appreciated. Thank you.
Side note: do not worry about the access modifiers of the instance variables. I left them as default for simplicity. I do know that they should be private with setters/getters or protected.