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接口。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM