优先队列的简单使用

import java.util.PriorityQueue;
import java.util.Random;

public class Chapter8 {
	public static void main(String[] args) {
		Random random = new Random();
		PriorityQueue<Student> queue = new PriorityQueue<Student>();
		for(int i = 0;i<10;i++){
			queue.add(new Student(random.nextInt(100)));
		}
		while(!queue.isEmpty()){
			System.out.print(queue.poll()+" ");
		}
	}
}

class Student implements Comparable<Student>{
	
	private int age;
	
	public Student(int age){
		this.age = age;
	}
	
	public String toString(){
		return age+"";
	}
	
	@Override
	public int compareTo(Student o) {
		return this.age - o.age; //从小到大
	}
	
}
输出:17 40 43 44 45 67 85 87 90 95 

你可能感兴趣的:(优先队列的简单使用)