`
linxizeng
  • 浏览: 102284 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Tiger学习 之 Queue

阅读更多
Queue:interface,先进先出,通过LinkedList类实现

offer方法,添加元素。类似add方法,但是offer返回boolean,不能添加时不会抛出异常
poll方法,删除(首端)元素,类似remove方法,但是poll返回boolean,不能删除时不会抛出异常

引用

Queue queue = new LinkedList();
queue.offer("a");
queue.offer("b");
queue.offer("c");
queue.remove();
System.out.println("queue values are: " + queue);

输出:queue values are: [b, c]


peek方法,取出首端值
引用

String peek = (String)queue.peek();
System.out.println("peek value is : " + peek);

输出:peek value is : a



PriorityQueue自动(按元素值)排序
引用

PriorityQueue priorityQueue = new PriorityQueue();
priorityQueue.offer(1);
priorityQueue.offer(3);
priorityQueue.offer(4);
priorityQueue.offer(2);
for(int i = 0; i < 4; i++) {
System.out.println("poll value is : " + priorityQueue.poll());
}
输出:
poll value is : 1
poll value is : 2
poll value is : 3
poll value is : 4


通过Comparator来做定义Queue的排序,也可以通过实现Comparable来比较排序

引用


eg1:compare返回正数是降序

PriorityQueue priorityQueue = new PriorityQueue(3,new Comparator(){
public int compare(Object o1, Object o2){
return (o2.hashCode()-o1.hashCode());
}
});
priorityQueue.offer(11);
priorityQueue.offer(14);
priorityQueue.offer(13);
priorityQueue.offer(12);

输出:
poll value is : 14
poll value is : 13
poll value is : 12
poll value is : 11


eg2:compare返回负数是升序

PriorityQueue priorityQueue = new PriorityQueue(3,new Comparator(){
public int compare(Object o1, Object o2){
return (o1.hashCode()-o2.hashCode());
}
});
priorityQueue.offer(11);
priorityQueue.offer(14);
priorityQueue.offer(13);
priorityQueue.offer(12);


输出:
poll value is : 11
poll value is : 12
poll value is : 13
poll value is : 14


==============================
Comparator,Comparable接口区别(资料)
  comparable是通用的接口,用户可以实现它来完成自己特定的比较,而comparator可以看成一种算法的实现,在需要容器集合 collection需要比较功能的时候,来指定这个比较器,这可以看出一种设计模式,将算法和数据分离。
前者应该比较固定,和一个具体类相绑定,而后者比较灵活,它可以被用于各个需要比较功能的类使用。可以说前者属于“静态绑定”,而后者可以“动态绑定”。

  一个类实现了Camparable接口表明这个类的对象之间是可以相互比较的。如果用数学语言描述的话就是这个类的对象组成的集合中存在一个全序。这样,这个类对象组成的集合就可以使用Sort方法排序了。
  而Comparator的作用有两个:
1. 如果类的设计师没有考虑到Compare的问题而没有实现Comparable接口,可以通过 Comparator来实现比较算法进行排序
2. 为了使用不同的排序标准做准备,比如:升序、降序或其他什么序
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics