PriorityQueue-最大堆/Comparator比较的写法(溢出问题)

今天利用PriorityQueue实现最大堆,写了一个bug。

原始写法:

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

用lambda简化后:

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

注意到,这里o2-o1是会产生溢出的,会导致结果不正确。

所以采用这种写法更好:

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

用lambda简化后:

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

Queue<Integer> heap = new PriorityQueue<>(Comparator.reverseOrder());
原文地址:https://www.cnblogs.com/angelica-duhurica/p/12592230.html