整数阵列的Java组合商

发布于 2025-02-01 11:17:20 字数 597 浏览 2 评论 0原文

我正在尝试将优先级的队列按第一个元素的值订购,但我遇到了一个问题,该问题表明,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

扮仙女 2025-02-08 11:17:20

谢谢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]);

德意的啸 2025-02-08 11:17:20

为了简单地回答您的问题,您是根据比较器要求返回布尔值,而不是整数。

简单地尝试以下内容:

PriorityQueue<int[]> kNearest = new PriorityQueue<>((a, b) -> Integer.compare(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:

PriorityQueue<int[]> kNearest = new PriorityQueue<>((a, b) -> Integer.compare(b[0],a[0]));

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文