0

I'm having issues implementing a Priority Queue in Java, namely with generic Array instantiation. I've got a basic class which represents each entry in the queue:

class Node<K, V> {
    K key;
    V value;
    Node(K key, V value) {
        this.key = key;
        this.value = value;
    }
}

Additionally, I've got my PQ class:

public class PriorityQueue<Node> {
    private Node[] data;

    PriorityQueue(Class<Node> type, int size) {
        data = (Node[]) Object[size];
    }
}

I keep getting ClassCastException errors when trying to create the array. Any help would be greatly appreciated.

flying_loaf_3
  • 397
  • 2
  • 3
  • 12
  • Aside from anything, `Node` in `PriorityQueue` is a type variable, it's not the `Node` class you also shown. That's confusing. – Andy Turner Sep 01 '21 at 08:44
  • Why are you passing in `type` if you're not using it? You can create an array reflectively [using a class](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Array.html#newInstance-java.lang.Class-int...-); however, you can't then invoke this generically. – Andy Turner Sep 01 '21 at 08:47
  • Sorry, that was an artefact from and old version; Is there a way of creating an array of Node objects? – flying_loaf_3 Sep 01 '21 at 12:03
  • I have tried the methods suggested in the linked forum post and those don't work for me as a result of compiler and runtime errors! – flying_loaf_3 Sep 01 '21 at 12:04
  • "I have tried the methods suggested in the linked forum post and those don't work for me as a result of compiler and runtime errors!" doesn't tell us which methods you tried, and what compiler and runtime errors you experienced. – Andy Turner Sep 01 '21 at 12:07

0 Answers0