0

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;}
}
void
  • 7,760
  • 3
  • 25
  • 43
  • 1
    I think this applies here: http://stackoverflow.com/questions/4862960/explicit-casting-from-super-class-to-subclass – Cong Hui May 01 '15 at 06:24

1 Answers1

1

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;
    }
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • It's the other way around: he's trying to cast an `Object[]` to a `Map.Entry[]`. – Jesper May 01 '15 at 06:27
  • Right, and since this cannot be done we either have to try something else or change the logic of the code. – Tim Biegeleisen May 01 '15 at 06:28
  • Alright thanks that helps me out. I'm going to change it up a bit. – Nick1995Carp May 01 '15 at 06:38
  • 1
    @TimBiegeleisen I meant this: in your answer you say "... because a `Map.Entry` array cannot be cast to an `Object` array", but it's the other way around: because an `Object` array cannot be cast to a `Map.Entry` array. – Jesper May 01 '15 at 07:07
  • 2
    Need to do `new AHEntry[size]` or `(AHEntry)new AHEntry, ?>[size]`. – Radiodef May 01 '15 at 13:51