java priorityqueue

java priorityqueue是怎样的呢?下面就让我们一起来了解一下吧:

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

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

参考范例:

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

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

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

*/

}

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

//矩形类

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

      */

}

}

以上就是小编的分享了,希望能够帮助到大家。

标签:java priorityqueue

免责声明:本内容来自橡树街平台创作者或收集于互联网公开资源,不代表橡树街网的观点和立场。如有侵权内容,请联系我们删除。联系邮箱:ihuangque@qq.com
相关推荐
  • java程序员都干什么
    java程序员都干什么
    08-05
  • java开发课程怎么样
    java开发课程怎么样
    08-05
  • java绝对值函数
    java绝对值函数
    08-05
  • java学习路线
    java学习路线
    08-05
  • Java用处具体有哪些作用
    Java用处具体有哪些作用
    08-05
  • Java认证考试时间
    Java认证考试时间
    08-05
  • Java程序设计是什么
    Java程序设计是什么
    08-05
  • java开发指什么
    java开发指什么
    08-05
  • java培训什么内容
    java培训什么内容
    08-05
  • Java认证考什么
    Java认证考什么
    08-05