Reputation: 13
So I'm trying to create a class that implements a heap using an array in order to make a prioritized list. In my constructor I want to create an array of Entry objects. Is this possible to do? I have done some generic casting before and I have tried everything that usually works for me. I feel like It should be possible but i can't figure it out.
This is the exception I get when I run it:
[Ljava.lang.Object; cannot be cast to [Llab09.Entry;
`public class ArrayHeap<K,V> implements PriorityQueue<K,V> {
`private Comparator<K> comp;
private Entry<K,V>[] data;
private int heapSize;
@SuppressWarnings({"unchecked"})
public ArrayHeap(int size, Comparator<K> c){
data = (Entry<K,V>[]) new Object[size]; // type casting array
heapSize = 0;
comp = c;
}
}
Also I'll throw in my nested Entry class to look at aswell.
protected static class AHEntry<K,V> implements Entry<K,V> {
private K k;
private V v;
public AHEntry(K key, V value){
k = key;
v = value;
}
public K getKey(){ return k;}
public V getValue(){ return v;}
public void setKey(K key){ k = key;}
public void setValue(V value){ v = value;}
}
Upvotes: 0
Views: 707
Reputation: 520908
The line data = (Entry<K,V>[]) new Object[size]
is resulting in a type cast error because an Object
array cannot be cast to a Map.Entry
array. The following code makes use of the custom AHEntry
class which you provided:
public class ArrayHeap<K,V> implements PriorityQueue<K,V> {
private Comparator<K> comp;
private Entry<K,V>[] data;
private int heapSize;
@SuppressWarnings({"unchecked"})
public ArrayHeap(int size, Comparator<K> c){
data = new (AHEntry<K, V>)new AHEntry<?, ?>[size];
heapSize = 0;
comp = c;
}
}
Upvotes: 1