java中的队列Queue是一个接口,LinkedList提供了方法来支持队列,所以可以作为队列的一种实现方法
其中peek用来返回队头,不移除,队列为空时返回null
offer将元素插入队尾;
poll和remove再返回队头元素的基础上删除元素,poll在队列为空时返回null。
import java.util.*;
public class QueueDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue<Integer> q=new LinkedList<Integer>();
Random rand=new Random(100);
for(int i=0;i<10;i++){
q.offer(rand.nextInt(100));
}
while(q.poll()!=null){
System.out.print(q.remove()+" ");
}
System.out.println();
}
}
优先队列在java中有了实现,要想在PriorityQueue中使用自己的类,类中要实现Comparable接口生成自然顺序,或者自己提供Comparator。
import java.util.*;
public class QueueDemo {
public static void printQ(Queue q){//这个Queue不用指明类型,挺神奇的
while(q.peek()!=null){
System.out.print(q.poll()+" ");
}
System.out.println();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PriorityQueue<Integer> p=new PriorityQueue<Integer>();
Random rand=new Random(47);
for(int i=0;i<10;i++)
p.offer(rand.nextInt(100));
printQ(p);
List<Integer> list=Arrays.asList(25,22,20,48,19,6,53,132,21);
p=new PriorityQueue<Integer>(list);
printQ(p);
p=new PriorityQueue<Integer>(list.size(),Collections.reverseOrder());//长生反序队列
printQ(p);
p.addAll(list);
printQ(p);
}
}