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;}
}
1

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

It's the other way around: he's trying to cast an Object[] to a Map.Entry[].
Right, and since this cannot be done we either have to try something else or change the logic of the code.
Alright thanks that helps me out. I'm going to change it up a bit.
@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.
Need to do new AHEntry[size] or (AHEntry<K, V>)new AHEntry<?, ?>[size].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.