"main" java.lang.ClassCastException: [Ljava.lang.Comparable; cannot be cast to [LNode;

68 views Asked by At

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)

1

There are 1 answers

0
Dorian Gray On

That is because an array of type Comparable[] cannot be cast to an array of type T[], if T is a proper subtype of Comparable. The @SuppressWarnings("unchecked") is supressing that warning.

You could declare the array of type Comparable<T> and cast where needed.