1

I don't understand the following behaviour of Java. The following code:

    Queue<Integer> minQueue = new PriorityQueue<>((a, b) -> a - b);
    Queue<Integer> maxQueue = new PriorityQueue<>((a, b) -> b - a);

    minQueue.offer(3);
    minQueue.offer(1);
    minQueue.offer(5);
    minQueue.offer(4);
    System.out.println(minQueue);

    maxQueue.offer(3);
    maxQueue.offer(1);
    maxQueue.offer(5);
    maxQueue.offer(4);
    System.out.println(maxQueue);

This results in

[1, 3, 5, 4]
[5, 4, 3, 1]

But why does the first one not result in [1, 3, 4, 5]?

  • 2
    See the linked question. In short: The queue is working as expected (just beware of integer overflow when using addition and subtraction, consider using [`Integer.compare`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Integer.html#compare(int,int)) as the body of the lambda instead), it's just the string representation which does not show up in any particular order. – Petr Janeček Oct 17 '22 at 09:58
  • Ah that is stupid of me, sorry and thank you for the answer. – user20142617 Oct 17 '22 at 10:01
  • 2
    When you need a `Comparator` you can also just use [`Comparator.naturalOrder()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Comparator.html#naturalOrder()) and [`Comparator.reverseOrder()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Comparator.html#reverseOrder()). – Holger Oct 17 '22 at 10:24
  • Not stupid at all, this is indeed unintuitive and not trivial to find right away. Good luck with your code! – Petr Janeček Oct 17 '22 at 10:31

0 Answers0