现在的位置: 首页 > 综合 > 正文

PriorityQueue

2018年12月12日 ⁄ 综合 ⁄ 共 868字 ⁄ 字号 评论关闭
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);
		}
		
	}

}

抱歉!评论已关闭.