在进行队列操作的时候,一般我们采用的是先进先出的队列模式
但是在某些特定场合我们可能希望这个队列里先让优先级高的元素出来,然后再让优先级低的元素出来,这里就需要用到Java5新增加的优先队列 数据结构
这个数据结构会自动按照排序加入元素,例如元素大小或字典顺序,但是如果加入我们的类,比较大小需要我们实现Comparator这个比较器
所以下面这个例子的主要部分:
PriorityQueue的创建 需要加入Comparator
Comparator的实现
Queue新的方法:poll()拉出排在第一个的元素,同时删除
peek()则只是拷贝出第一个元素但不删除
这个数据结构实现可以采用链表结构实现,插入排序
package com.ylf;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
UnionCountry union = new UnionCountry();
Country c1 = new Country(3);
Country c2 = new Country(6);
Country c3 = new Country(4);
Country c4 = new Country(1);
Country c5 = new Country(9);
//早期进来来三个国家
union.addCountry(c1);
union.addCountry(c2);
union.addCountry(c3);
//这时候发生了争斗 ,把最差的拉出来,看下是谁拉后退
System.out.println("left:"+union.getSize());
System.out.println("get out man:"+union.pollCountry().toString());
System.out.println("left:"+union.getSize());
//再进来两个国家
union.addCountry(c4);
union.addCountry(c5);
System.out.println("left:"+union.getSize());
System.out.println("get out man:"+union.pollCountry().toString());
System.out.println("get out man:"+union.pollCountry().toString());
System.out.println("get out man:"+union.pollCountry().toString());
System.out.println("get out man:"+union.pollCountry().toString());
System.out.println("left:"+union.getSize());
}
}
/**
* 假设联合国存放来一个队列,记录了所有国家的实力
* @author ylf
*
*/
class UnionCountry{
CountryComparator comparator = null;
PriorityQueue<Country> queue = null;
public UnionCountry() {
comparator = new CountryComparator();//优先级比较器
queue = new PriorityQueue<Country>(10,comparator);
}
public void addCountry(Country c){
queue.add(c);
}
public Country pollCountry(){
return queue.poll();
}
public int getSize(){
return queue.size();
}
class CountryComparator implements Comparator<Country>{
@Override
public int compare(Country o1, Country o2) {
return o1.power-o2.power;
}
}
}
class Country{
public int power;
public Country(int power){
this.power = power;
}
public String toString(){
return power+" ";
}
}
left:3
get out man:3
left:2
left:4
get out man:1
get out man:4
get out man:6
get out man:9
left:0