I am trying to declare and assign an array while using generics and I'm having a little bit of trouble with this. I noticed that it was impossible to assign an array normally using generics. I found this work around, but it doesn't seem to work for me. It outputs a NullPointerException once it gets to the Array.newInstance(c,capacity). I'm just expecting this code to declare the array. Any ideas why this won't function the way it's expected to?
public class MyHeap<T extends Comparable<T>> implements Heap<T> {
Class<T> type;
T[] heap;
int size;
int capacity;
MyHeap(int x){
capacity = x;
size = 0;
arraySet(type, capacity);
}
private void arraySet(Class<T> c, int capacity){
@SuppressWarnings("unchecked")
final T[] heap = (T[]) Array.newInstance(c, capacity);
this.heap = heap;
}
}