2

I searched a bit and looks like a PriorityQueue work like a min-heap by default in Java. So, why override the comparator? I have seen people do it even for integers. Am I missing something here? I am new to java.

I tried both of the below codes to use in a leetcode solution requiring min-heap implementation and both got accepted. Here is a snippet:

// Implementing comparator
PriorityQueue<Integer> minHeap = new PriorityQueue<>(10,new Comparator<Integer>() {
    public int compare(Integer a, Integer b) {
        return a - b;
    }
});

// Not implementing comparator - why can't we just do this?
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
Black Mamba
  • 13,632
  • 6
  • 82
  • 105
Saikip
  • 21
  • 4
  • a) they didn't know what they were doing and copy and pasted it from somewhere. b) the did know what they were doing but wanted a reminder of which ordering it used by default – Ryan Vettese Feb 06 '19 at 06:42
  • The only way to know why would be to ask *those people*. Any answer here would be speculation. – Raedwald Feb 06 '19 at 06:44
  • Thank you. I was wondering if there was some technical explanation that I did not know of. – Saikip Feb 07 '19 at 19:41

1 Answers1

2

In this case the Comparator indeed seems redundant. If you don't explicitly pass a Comparator to PriorityQueue's constructor, it will use natural ordering, which is exactly what this Comparator implements.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Not exactly. The comparator using `a - b` is obviously meant to do the same as the natural order, but actually is *broken*, as this subtraction can overflow. The maximum distance between two `int` values may exceed `Integer.MAX_VALUE`. It might be that the author of this code even replaced the natural order by this deliberately, thinking of this being a “clever” optimization over the straight-forward `int` comparison, in which case, it might be a heavy task to break this developer’s habit… – Holger Feb 12 '19 at 17:02