I'm implementing a set of data structures and decided to try an implementation of a maxheap through an array, since it is one of the common implementations for maxheaps. To do that, I have an interface called MaxHeap<T>
which accepts Comparable
types T
and the following class signature:
public class ArrayMaxHeap<T extends Comparable<T>> implements MaxHeap<T> {
T
has to be Comparable
, or else I won't be able to compare the elements with one another when doing additions and removals from the heap. The problem lies with the constructor of the class:
public class ArrayMaxHeap<T extends Comparable<T>> implements MaxHeap<T> {
private T[] data;
private int last;
private static final int INIT_CAPACITY = 10;
/**
* Creates an empty ArrayMaxHeap with the default capacity.
*/
public ArrayMaxHeap(){
data = (T[])(new Object[INIT_CAPACITY]);
last = 0;
}
The type casting of data
is throwing a ClassCastException
, because the downcasting from Object
, which is not Comparable
, is unsafe. I've hit a wall with this and am not sure how I would go about implementing the constructor. Any help would be appreciated.
This is kind of a limitation of generics. Instead just declare your array as Object[]
and cast the element you try to return. Something similar to what ArrayList
does.
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
where elementData
is
private transient Object[] elementData;
If you control what is going in, there's no problem.
I'm going to link the question and answer in Rohit's comment because it's brilliant.