栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java对PriorityQueue的Comparator()进行重写

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java对PriorityQueue的Comparator()进行重写

当PriorityQueue存储自定义类(如:链表)或数组时,对PriorityQueue的Comparator()进行重写

1.PriorityQueue()存储自定义类(如:链表)
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class erchadui {
    public static void main(String[] args){
    ListNode list1 = new ListNode();//如:1->4->5,
    ListNode list2 = new ListNode();//如:2->6,
	PriorityQueue que1 = new PriorityQueue(new Comparator() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
            // 按链表头结点的val值进行降序排序
                return o1.val - o2.val;
            }
        });
	}
}
2.PriorityQueue()存储Integer数组
public static void main(String[] args){
//        int[] nums = new int[]{1,2,3,4,5};
//        int[] nums1 = new int[]{8,2,3,4,5};
//        int[] nums2 = new int[]{0,2,3,4,5};
        Integer[] nums = new Integer[]{1,2,3,4,5};
        Integer[] nums1 = new Integer[]{8,2,3,4,5};
        Integer[] nums2 = new Integer[]{0,2,3,4,5};
        PriorityQueue que2 = new PriorityQueue(new Comparator() {
            @Override
            public int compare(Integer[] o1, Integer[] o2) {
            // 按Integer数组头结点进行降序排序
            // 因为自动拆装箱所以可以换成 return o[2]-o[1];
                return o2[0].compareTo(o1[0]);
            }
        });
        que2.add(nums);
        que2.add(nums1);
        que2.add(nums2);
        while (que2.size()>0){
            Integer[] tmp = que2.poll();
            for(int i = 0; i < tmp.length; i++){
                System.out.print(tmp[i] + " ");
            }
            System.out.println();
        }
    }

可参考:
[1]Java的优先队列PriorityQueue详解

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/846100.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号