为什么我无法输入:BlockingQueue a = new PriorityQueue<>(2);

huangapple go评论56阅读模式
英文:

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&lt;Integer&gt; a = new PriorityBlockingQueue&lt;&gt;(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&lt;T&gt; 的泛型参数,因为没有任何有效的 T 存在。话虽如此,“无法推断参数” 听起来可能是由于代码中其他地方的这个变化所导致的副作用。

查阅关于 BlockingQueue文档,您应该使用 "所有已知实现类:" 下的其中一个类,找到一个带有 BlockingQueue 的库,或者实现您自己的队列。

您的另一个选择是使用另一种类型的队列,比如在 BlockingQueue&lt;Integer&gt; 的位置上使用 AbstractQueue&lt;Integer&gt;

英文:

Well for starters, PriorityQueue is not a BlockingQueue. It wont be able to infer any generic arguments for PriorityQueue&lt;T&gt; 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&lt;Integer&gt; in place of BlockingQueue&lt;Integer&gt;.

答案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&lt;Integer&gt; ls = new ArrayList&lt;&gt;():, which will not compile.

huangapple
  • 本文由 发表于 2020年10月4日 05:10:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64189043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定