import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
class FixSizedPriorityQueue<E extends Comparable> extends PriorityQueue<E> {
private int maxSize;
public FixSizedPriorityQueue(int size) {
super(size, new Comparator<E>() {
public int compare(E e1, E e2) {
return e1.compareTo(e2);//小顶堆;如果是e2.compareTo(e1)是大顶堆
}
});
this.maxSize = size;
}
public boolean put(E e) {
if (this.size() < maxSize) {
return this.offer(e);
}
E peek = this.peek();
if (e.compareTo(peek) > 0) {
this.poll();
this.offer(e);
}
return false;
}
}
public class BiFeat {
public static void main(String[] args) {
// TODO Auto-generated method stub
FixSizedPriorityQueue<Integer> qu = new FixSizedPriorityQueue<Integer>(3);
qu.put(4);
qu.put(1);
qu.put(5);
qu.put(10);
qu.put(9);
qu.put(3);
qu.put(6);
for (Integer i : qu) {
System.out.println(i);
}//按照的是在数组中的顺序输出的
System.out.println(qu);
while (true) {//有序输出
Integer i = qu.poll();
if ( i == null) {
break;
}
System.out.println(i);
}
}
}
PriorityQueue
最新推荐文章于 2024-07-24 19:24:20 发布