0

I have started learing java generics and this is my priority queue implementation:

public class MinPQ<Key> implements Iterable<Key> {
   private Key[] pq;                    // store items at indices 1 to n
   private int n;                       // number of items on priority queue
   private Comparator<Key> comparator;  // optional comparator

   public MinPQ(Key[] keys) {
        n = keys.length;
        pq = (Key[]) new Object[keys.length + 1];
        .....
        .....
    }
}

And this is my main class :

public class Demo {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            int[] ar = {1,2,3};
            MinPQ<Integer> pq = new MinPQ<Integer>(ar);
        }
}

But here I get an error stating "The constructor MinPQ(int[]) is undefined" can someone please help me find the issue here ?

Ravi Kumar
  • 45
  • 4
  • Does this answer your question? [What's the reason I can't create generic array types in Java?](https://stackoverflow.com/questions/2927391/whats-the-reason-i-cant-create-generic-array-types-in-java) – DontKnowMuchBut Getting Better May 29 '20 at 20:46
  • Don't create arrays of generic type as you have problems with type erasure. Instead use a `List` or other generic collection. – DontKnowMuchBut Getting Better May 29 '20 at 20:47
  • As @DontKnowMuchButGettingBetter said, you will probably have an easier time with `List`. However, as an exercise try changing `ar` to `Integer[]` rather than `int[]`. – roadkill May 29 '20 at 20:50

1 Answers1

1

You can't use primitive types with generics. Just change:

int[] ar = {1,2,3}; 

to:

Integer[] ar = {1,2,3};

or box it with

IntStream.of(ar).boxed().toArray(Integer[]::new)

Basically you're trying to pass an int[] to a constructor which requires Integer[], because of MinPQ<Integer> declaration. So, in tehory it should work if you declared it as MinPQ<int> - but as stated at the beginning we can't use primitive types for generics.

pafau k.
  • 1,610
  • 11
  • 20