0

I'm trying to make a priority queue ADT in Java using an array. I don't know Java very well but I'm getting the hang of it. The only problem I'm having is making an array of a class I made called QueueElement. I need the array to work with any data type so I create a new ArrayList of integers for example like this:

ArrayQueue<Integer> AQ = new ArrayQueue<Integer>(10);

The problem is I can't have an array of just a generic type T because I need to know the priority of each element in the array. So I made a class called ArrayElement which contains the data(type T) and the priority(type int). (priority can be between 1 and 5 inclusive). But it won't let me make that array. Here's my code:

public class ArrayQueue<T> {

  private QueueElement[] arr;
  private int total, front, rear, MAX_SIZE;

  public class QueueElement {
      T data;
      int priority;

      public QueueElement(T d, int p) {
          data = d;
          priority = p;
      }
  }

  //constructor
  public ArrayQueue(int size) {
      //it won't let me cast this array to the type QueueElement
      arr = (QueueElement[]) new Object[size];
      //arr = new QueueElement[size]; doesn't work either
      front = 0;
      rear = -1;
      total = 0;
      MAX_SIZE = size;
  }
}

If you have any idea on how I can do this it would help me a lot. Thanks.

  • Please only tag your question with relevant tags. This is clearly Java code, not C++ as you had tagged it. – bcsb1001 Nov 01 '17 at 02:48
  • You can refer to this link: More especially to this part: "you can't create an array of your parameterized type. Arrays are covariant. That means they retain the type of their elements at runtime. Java's generics are not. They use type erasure to basically mask the implicit casting that is going on. It's important to understand that." [generic-arrays-in-java](https://stackoverflow.com/questions/1817524/generic-arrays-in-java) – Allan Nov 01 '17 at 02:54

0 Answers0