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]);
pdewilde
  • 176
  • 1
  • 1
  • 10
  • 1
    new PriorityQueue((a, b) -> b[0] > a[0]) does not return an array – z atef May 25 '22 at 04:11
  • Thank you! I forgot the diamond operator. I also messed up my comporator by returning a boolean rather than an int. Fixed version: ``` PriorityQueue kNearest = new PriorityQueue((a, b) -> b[0] - a[0]);``` – pdewilde May 25 '22 at 04:26

2 Answers2

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

pdewilde
  • 176
  • 1
  • 1
  • 10
0

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.

sbsatter
  • 591
  • 3
  • 22
  • 1
    This is half right. The problem is that `i - j` doesn't return the required values for ALL values of `i` and `j`. Use Integer.compare(int, int)`. See https://stackoverflow.com/questions/2728793 – Stephen C May 25 '22 at 04:40
  • You are correct, this is something many often miss and should in fact be the better practice. Thanks I updated the answer. – sbsatter May 25 '22 at 05:00