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

103 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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>.

0
On

The code in the title doesn't compile because PriorityQueue does not implement nor extend BlockingQueue. It's like doing this: LinkedList<Integer> ls = new ArrayList<>():, which will not compile.