当前位置:懂科普 >

IT科技

> java priorityqueue

java priorityqueue

java中的priorityqueue一般也就是代表优先队列。

这是属于Queue接口的实现,能够对其中元素进行排序,还能放基本数据类型的包装类或是自定义的类,而对于基本数据类型的包装类,优先队列中元素一般是默认排列顺序为升序排列的。

java priorityqueue

参考范例:

队列保存的是基本数据类型的包装类,具体代码为:

//自定义比较器,降序排列

static Comparator<Integer> cmp = new Comparator<Integer>() {

      public int compare(Integer e1, Integer e2) {

        return e2 - e1;

      }

    };

public static void main(String[] args) {

        //不用比较器,默认升序排列

        Queue<Integer> q = new PriorityQueue<>();

        q.add(3);

        q.add(2);

        q.add(4);

        while(!q.isEmpty())

        {

            System.out.print(q.poll()+" ");

        }

        /**

         * 输出结果

         * 2 3 4 

         */

        //使用自定义比较器,降序排列

        Queue<Integer> qq = new PriorityQueue<>(cmp);

        qq.add(3);

        qq.add(2);

        qq.add(4);

        while(!qq.isEmpty())

        {

            System.out.print(qq.poll()+" ");

        }

        /**

         * 输出结果

         * 4 3 2 

         */

}

java priorityqueue 第2张

队列保存的是自定义类,具体代码为:

//矩形

class Node{

    public Node(int chang,int kuan)

    {

        this.chang=chang;

        this.kuan=kuan;

    }

    int chang;

    int kuan;

}

public class Test {

 //自定义比较类,先比较长,长升序排列,若长相等再比较宽,宽降序

    static Comparator<Node> cNode=new Comparator<Node>() {

        public int compare(Node o1, Node o2) {

            if(o1.chang!=o2.chang)

                return o1.chang-o2.chang;

            else

                return o2.kuan-o1.kuan;

        }

        

    };

    public static void main(String[] args) {

        Queue<Node> q=new PriorityQueue<>(cNode);

        Node n1=new Node(1, 2);

        Node n2=new Node(2, 5);

        Node n3=new Node(2, 3);

        Node n4=new Node(1, 2);

        q.add(n1);

        q.add(n2);

        q.add(n3);

        Node n;

        while(!q.isEmpty())

        {

            n=q.poll();

            System.out.println("长: "+n.chang+" 宽:" +n.kuan);

        }

  /**

   * 输出结果

   * 长: 1 宽:2

   * 长: 2 宽:5

   * 长: 2 宽:3

   */

    }

}

标签: priorityqueue java
  • 文章版权属于文章作者所有,转载请注明 https://dongkepu.com/itkeji/ywv9e5.html