海诗网 知识百科 java(java是什么)

java(java是什么)

java, java中的Priorityqueue一般代表优先级队列。

这是Queue接口的实现,可以对里面的元素进行排序,也可以放基本数据类型的包装类或者自定义类。对于基本数据类型的包装类,默认情况下,优先级队列中的元素通常按升序排列。

java是什么

参考示例:

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

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

static ComparatorInteger cmp=new ComparatorInteger() {

public int compare(Integer e1, Integer e2) {

return e2 - e1;

}

};

public static void main(String[] args) {

//没有比较器,默认排列是升序。

QueueInteger q=new PriorityQueue();

q.add(3);

q.add(2);

q.add(4);

while(!q.isEmpty())

{

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

}

/**

*输出结果

* 2 3 4

*/

//使用自定义比较器按降序排序。

QueueInteger 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是什么

队列存储自定义类,具体代码为:

//矩形类

class Node{

public Node(int chang,int kuan)

{

this.chang=chang;

this.kuan=kuan;

}

int chang;

int kuan;

}

public class Test {

//用户自定义的比较类,先长后短,按长度升序排列,外观相等则更宽,降序排列则更宽。

static ComparatorNode cNode=new ComparatorNode() {

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) {

QueueNode 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 .宽);

}

/**

*输出结果

*长度:1宽度:2

*长:2宽:5

*长:2宽:3

*/

}

}

以上是边肖的分享,希望对大家有所帮助。

java,以上就是本文为您收集整理的java最新内容,希望能帮到您!更多相关内容欢迎关注。

本文来自网络,不代表海诗网立场,转载请注明出处:https://www.hallse.com/n/169245.html
      

ping(pingpong)

发表回复
联系我们
联系我们

在线咨询: QQ交谈

邮箱: 3587015498@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们
微信扫一扫关注我们
关注微博
返回顶部