zoukankan      html  css  js  c++  java
  • java中PriorityQueue优先队列使用方法

    import java.util.Comparator;
    import java.util.PriorityQueue;
    import java.util.Queue;
    
    public class test {
        private String name;
        private int population;
    
        public test(String name, int population) {
            this.name = name;
            this.population = population;
        }
    
        public String getName() {
            return this.name;
        }
    
        public int getPopulation() {
            return this.population;
        }
    
        public String toString() {
            return getName() + "-" + getPopulation();
    
        }
    
        public static void main(String[] args) {
            Comparator<test> OrderIsdn = new Comparator<test>() {
                public int compare(test o1, test o2) {
                    int numbera = o1.getPopulation();
                    int numberb = o2.getPopulation();
                    if (numberb > numbera) {
                        return 1;
                    }
    
                    else if (numberb < numbera) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
    
            };
            
            Queue<test> priorityQueue=new PriorityQueue<test>(11,OrderIsdn);
            
            test t1=new test("t1",1);
            test t2=new test("t2",2);
            
            test t3=new test("t3",3);
            test t4=new test("t4",0);
            priorityQueue.add(t1);
            priorityQueue.add(t2);
            priorityQueue.add(t3);
            priorityQueue.add(t4);
            System.out.println(priorityQueue.poll().toString());
    
        }
    
    }

    优先队列是不同于先进先出队列的另一种队列。每次从队列中取出的是具有最高优先权限的元素。如果不提供Comparator接口的话,优先队列中元素默认按照自然顺序排列,也就是

    数字默认是最小的在队列头,字符串则按字典排序。如果想实现按照自己的意愿进行优先级排列的话,需要实现comparator接口。

  • 相关阅读:
    dockerfile 详解
    kubectl简介
    关于高级事件的使用
    关于拖拽延伸出来的一些效果
    照片墙的制作过程及其出现的问题
    关于360度全景照片的问题总结
    实战演练-记账本App (五)
    人月神话阅读笔记02
    实战演练-记账本App(四)
    实战演练-记账本App(三)
  • 原文地址:https://www.cnblogs.com/ilxx1988/p/3309204.html
Copyright © 2011-2022 走看看