PriorityQueue- maximum heap Comparator compare the wording / (overflow)

Today, the use of PriorityQueue maximum heap, wrote a bug.

Original wording:

        Queue<Integer> heap = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });

After lambda simplified:

Queue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2 - o1);

Noted here o2-o1 will overflow, it will lead to incorrect results.

Therefore, the use of such an approach is better:

        Queue<Integer> heap = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });

After lambda simplified:

Queue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2.compareTo(o1));

which is

Queue<Integer> heap = new PriorityQueue<>(Comparator.reverseOrder());

Guess you like

Origin www.cnblogs.com/angelica-duhurica/p/12592230.html