Queue,PriorityQueue学习

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Set;

public class TestPriorityQueue {
	public static void main(String[] args){
		PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();
		Random random = new Random(47);
		for(int i=0; i<10; i++){
			priorityQueue.offer(random.nextInt(i+10));
		}
		printQ(priorityQueue);

		List<Integer> ints = Arrays.asList(25, 22, 20, 18, 14, 9, 3, 1, 1, 2, 3, 9, 14, 18, 21, 23, 25);
		priorityQueue = new PriorityQueue<Integer>(ints);
		printQ(priorityQueue);

		priorityQueue = new PriorityQueue<>(ints.size(), Collections.reverseOrder());
		priorityQueue.addAll(ints);
		printQ(priorityQueue);

		String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION";
		List<String> strings = Arrays.asList(fact.split(""));
		PriorityQueue<String> stringPriorityQueue = new PriorityQueue<String>(strings);
		printQ(stringPriorityQueue);

		stringPriorityQueue = new PriorityQueue<String>(strings.size(), Collections.reverseOrder());
		stringPriorityQueue.addAll(strings);
		printQ(stringPriorityQueue);

		Set<Character> charSet = new HashSet<Character>();
		for(char c : fact.toCharArray()){
			charSet.add(c);
		}
		PriorityQueue<Character> characterPQ = new PriorityQueue<Character>(charSet);
		printQ(characterPQ);

	}

	public static void printQ(Queue queue){
		while(queue.peek() != null){
			System.out.print(queue.remove()+" ");
		}
		System.out.println();
	}
}

运行结果为:

0 1 1 1 1 1 3 5 8 14 
1 1 2 3 3 9 9 14 14 18 18 20 21 22 23 25 25 
25 25 23 22 21 20 18 18 14 14 9 9 3 3 2 1 1 
       A A B C C C D D E E E F H H I I L N N O O O O S S S T T U U U W 
W U U U T T S S S O O O O N N L I I H H F E E E D D C C C B A A        
  A B C D E F H I L N O S T U W

注意:

PriorityQueue可以传入Comparator来规定排序的顺序,主要是Comparator中的compare函数。

About: happyhls


发表评论

电子邮件地址不会被公开。 必填项已用*标注