0

The questions ask how to find n-th ugly number, which is a number only have factors 3,5,6 . For that question, design an algorithm to find the kth ugly number. In order to solve that problem, I use PriorityQueue to store possible qualified ugly numbers, PriorityQueue will sort the numbers in ascending order. But if I initialize the queue in the following way, the error comes up, it says "unexpected type, Queue queue = new PriorityQueue()".

public long kthPrimeNumber(int k) {
    // write your code here
    if(k<=0){
        return -1;
    }
    Queue<int> queue = new PriorityQueue<int>();
    queue.add(3);
    queue.add(5);
    queue.add(7);

    for(int i=1; i<k;i++){
        int curr = (int)queue.poll();
        queue.add(curr*3);
        queue.add(curr*5);
        queue.add(curr*7);

    }
    return (long)((int)queue.poll());

}
  • You can't use primitives as type values ( i. e. replace `Queue` with `Queue` and `new PriorityQueue()` with `new PriorityQueue()` ) – morgano Feb 18 '16 at 22:12

1 Answers1

1

You cannot use primitive types as generic type parameters. You need something like this

Queue<Integer> queue = new PriorityQueue<Integer>();
Bunti
  • 1,730
  • 16
  • 20
  • Does that mean using Integer works but int doesn't? – Jiaying Yang Feb 22 '16 at 04:01
  • Exactly. You can find the reason why Java doesn't support primitive type parameters for generic types. Basically it's because primitive types do not extend `Object` type so that casting is impossible. Generics were added later and in order to be backward compatible these generic types should be erased at runtime. With Generics Java compiler ensures that types are compatible and it adds the cast for the developer. You can find more info [here](http://stackoverflow.com/questions/18021218/create-a-list-of-primitive-int) – Bunti Feb 22 '16 at 06:20