Search code examples
javaqueuepriority-queueblockingqueue

Why I can't type: BlockingQueue<Integer> a = new PriorityQueue<>(2);


The code I type in title doesn't compile. It says: Cannot infer arguments.

After that I did BlockingQueue<Integer> a = new PriorityBlockingQueue<>(2); which compiles just fine. What was my mistake, so I can avoid it next time?

Yes, I know that constructor in Queue interface has parameter(2) for initial capacity, while in BlockingQueue parameter(2) represents max elements. Does this have anything to do with the error?


Solution

  • Well for starters, PriorityQueue is not a BlockingQueue. It wont be able to infer any generic arguments for PriorityQueue<T> because there is no T that will be valid. That being said, Cannot infer arguments sounds like it may be due to a side effect of this change somewhere else in your code.

    Looking at the documentation for BlockingQueue, you should instead use one of the classes under "All Known Implementing Classes:", find a library with BlockingQueues, or implement your own.

    Your other option is to use another type of queue instead, like AbstractQueue<Integer> in place of BlockingQueue<Integer>.