整数阵列的Java组合商
我正在尝试将优先级的队列按第一个元素的值订购,但我遇到了一个问题,该问题表明,Crunder正在抱怨阵列在我的comporator lambda表达式中重新定位。对我搞砸了什么想法吗?
PriorityQueue< int []> nearest = new Priorityqueue(((a,b) - > b [0]> a [0]);
>
Line 22: error: array required, but Object found
PriorityQueue<int[]> kNearest = new PriorityQueue((a, b) -> b[0] > a[0]);
^
Line 22: error: array required, but Object found
PriorityQueue<int[]> kNearest = new PriorityQueue((a, b) -> b[0] > a[0]);
I'm trying to make a priority queue that orders integer arrays by the value of the first element, but I am running into an issue that the complier is complaining that an array is requred in my Comporator lambda expression. Any idea on what I'm screwing up?
PriorityQueue<int[]> kNearest = new PriorityQueue((a, b) -> b[0] > a[0]);
Line 22: error: array required, but Object found
PriorityQueue<int[]> kNearest = new PriorityQueue((a, b) -> b[0] > a[0]);
^
Line 22: error: array required, but Object found
PriorityQueue<int[]> kNearest = new PriorityQueue((a, b) -> b[0] > a[0]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
谢谢Kiran和Zatef!我忘记了钻石操作员。我还通过返回布尔而不是int来弄乱了我的汇编。
固定版本:
PriorityQueue&lt; int []&gt; nearest =新的PriorityQueue&lt; int []&gt;((a,b) - &gt; b [0] - a [0]);
>Thank you Kiran and zatef! I forgot the diamond operator. I also messed up my comporator by returning a boolean rather than an int.
Fixed version:
PriorityQueue<int[]> kNearest = new PriorityQueue<int[]>((a, b) -> b[0] - a[0]);
为了简单地回答您的问题,您是根据比较器要求返回布尔值,而不是整数。
简单地尝试以下内容:
与[0]相比,这将根据B [0]的较小值订购项目。
这里的比较器检查平等并返回以下内容:
'&lt; 时,当第一个参数为较小的'0'时,0'(例如-1)
当两个参数相等
。 '&gt; 0'(例如1)当第二个参数为较小
更新:如@Stephen C在评论中指出的那样,减法并不能完全证明。有关详细信息,请查看 this 。答案已更新以利用Integer.compare(INT,INT)方法。
To simply answer your question, you are returning a boolean instead of an integer as required by the comparator.
Try simply the following:
This will order the items based on smaller values of b[0] in comparison to a[0].
The comparator here checks for equality and returns the following:
'< 0' (e.g. -1) when the first parameter is smaller
'0' when both the params are equal.
'> 0' (e.g. 1) when the 2nd parameter is smaller
Update: As pointed out by @Stephen C in comments, a subtraction is not full proof. For details, please view this. The answer is updated to make use of the Integer.compare(int, int) method.