java中Queue的使用

Queue表示先进先出的队列:

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

public class QueueDemo {
	
	public static void printQ(Queue queue){
		while (queue.peek()!=null){
			System.out.print(queue.remove()+" ");
		}
		System.out.println();
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Queue queue=new LinkedList();
		Random random=new Random(47);
		for(int i=0;i<10;i++){
			queue.offer(random.nextInt(i+10));
		}
		printQ(queue);
		Queue qc =new LinkedList();
		for(char c:"fjaslhlncad".toCharArray()){
			qc.offer(c);
		}
		printQ(qc);
	}
}

优先队列:

import java.awt.List;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Set;

public class PriorityQueueDemo {
	
	public static void main(String[] args) {
		PriorityQueue priorityQueue=new PriorityQueue();
		Random random=new Random(47);
		for (int i = 0; i <10; i++) {
			priorityQueue.offer(random.nextInt(i+10));
		}
		QueueDemo.printQ(priorityQueue);
		java.util.List ints=Arrays.asList(13,2,13,43,53,1,21,43,535,6435,232,11,12,32,98);
		priorityQueue=new PriorityQueue(ints);
		QueueDemo.printQ(priorityQueue);
		priorityQueue=new PriorityQueue(ints.size(),Collections.reverseOrder());
		priorityQueue.addAll(ints);
		QueueDemo.printQ(priorityQueue);
		String fact="EDUCATION SHOULD ESCHEN OBFUSATION";
		java.util.List string=Arrays.asList(fact.split(" "));
		PriorityQueue stringPQ=new PriorityQueue(string);
		QueueDemo.printQ(stringPQ);
		stringPQ=new PriorityQueue(string.size(),Collections.reverseOrder());
		stringPQ.addAll(string);
		QueueDemo.printQ(stringPQ);
		Set charSet=new HashSet();
		for(char c: fact.toCharArray()){
			charSet.add(c);
		}
		PriorityQueue characterPQ=new PriorityQueue(charSet);
		QueueDemo.printQ(characterPQ);	
	}
}


你可能感兴趣的:(java)