英文:
Why I can't type: BlockingQueue<Integer> a = new PriorityQueue<>(2);
问题
以下是您要翻译的内容:
我输入标题的代码无法编译。它显示:无法推断参数。
在那之后,我执行了 BlockingQueue<Integer> a = new PriorityBlockingQueue<>(2);,这个编译得很好。我的错误是什么,下次我可以避免这种情况吗?
是的,我知道 Queue 接口中的构造函数有参数(2)表示初始容量,而在 BlockingQueue 中,参数(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?
答案1
得分: 1
好的,以下是翻译好的部分:
首先,PriorityQueue 并不是一个 BlockingQueue。它将无法推断出任何适用于 PriorityQueue<T> 的泛型参数,因为没有任何有效的 T 存在。话虽如此,“无法推断参数” 听起来可能是由于代码中其他地方的这个变化所导致的副作用。
查阅关于 BlockingQueue 的文档,您应该使用 "所有已知实现类:" 下的其中一个类,找到一个带有 BlockingQueue 的库,或者实现您自己的队列。
您的另一个选择是使用另一种类型的队列,比如在 BlockingQueue<Integer> 的位置上使用 AbstractQueue<Integer>。
英文:
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>.
答案2
得分: 1
标题中的代码无法编译,因为PriorityQueue没有实现也没有扩展BlockingQueue。这就好比执行这样的操作:LinkedList<Integer> ls = new ArrayList<>();,这将无法编译。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论