6

I want to compare by the second element of the array [[0, 30],[5, 10],[15, 20]].

PriorityQueue<int[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);

But I am getting an error as below

Line 8: error: array required, but Object found PriorityQueue<Integer[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]); ^ Line 8: error: array required, but Object found PriorityQueue<Integer[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);

^ 2 errors

Suhas Ramesh
  • 63
  • 1
  • 1
  • 5
  • Does this answer your question? [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Amongalen Jul 06 '20 at 12:11
  • 1
    In short, you shouldn't use a raw type here. `new PriorityQueue<>(intervals.length, (a, b) -> a[1] - b[1])` works – Amongalen Jul 06 '20 at 12:13

6 Answers6

4

You should cast a to int array first.

PriorityQueue<int[]> heap = new PriorityQueue(intervals.length, (a, b) -> ((int[])a)[1] - ((int[])b)[1]);
ARoger
  • 83
  • 8
3

You could use Integer.compare

PriorityQueue<int[]> heap = new PriorityQueue<>(intervals.length, (a,b) -> Integer.compare(a[1],b[1]));
Happy Coder
  • 1,293
  • 1
  • 19
  • 35
2

Well, in your example, you have a 2D array; however, in your code snippet, you're assuming that a single-dimensional array should be kept in the Queue. So, which is your question? are you sure you want to maintain the Queue of 2D arrays? that doesn't mean, that you would have a Queue of pairs/tuples, that means, that each element in that queue, will be a discrete 2D array object. And in this case, probably each array will have more than one element.. and that means, that you should most likely iterate through them.. but if you're sure what you want with this code to be achieved and it's correct, then you can compare first elements like this:

    PriorityQueue<int[][]> heap = new PriorityQueue<int[][]>((a, b) -> {
        if (a[0][0] > b[0][0]) {
            return 1; //change according to your logic
        } else if (a[0][0] < b[0][0]) {
            return -1; //change according to your logic
        } else {
            return 0; //change according to your logic
        }
    });
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
2

Just add "<>" after PriorityQueue:

PriorityQueue<int[]> heap = new PriorityQueue<>(intervals.length, (a, b) -> a[1] - b[1]);
1

You can use:

PriorityQueue<int[]> pq = new PriorityQueue<>(intervals.length,
                             Comparator.comparingInt(interval -> interval[1]));
0

Your code is missing one vital syntax. You can add <> or <int[]> to the RHS of the assignment statement and it will work. So the line statement will become:

PriorityQueue<int[]> heap = new PriorityQueue<int[]>(intervals.length, (a, b) -> a[1] - b[1]);
Kenart
  • 285
  • 3
  • 14