I am trying to create a Generic class like bellow
public class MyMinHeap<T extends Comparable<T>>
{
// To store array of elements in heap
public T[] heapArray;
// max size of the heap
public int capacity;
// Constructor
@SuppressWarnings("unchecked")
public MyMinHeap(int n)
{
capacity = n;
heapArray = (T[]) new Comparable[capacity];
current_heap_size = 0;
}
MyMinHeap<Node> minHeap = new MyMinHeap<Node>(amount);
After populating minHeap.heapArray When trying to access minHeap.heapArray[0] getting error Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Comparable; cannot be cast to [LNode; at HalloJavaApp.main(HalloJavaApp.java:111)
That is because an array of type
Comparable[]cannot be cast to an array of typeT[], ifTis a proper subtype ofComparable. The@SuppressWarnings("unchecked")is supressing that warning.You could declare the array of type
Comparable<T>and cast where needed.