本文依据PriorityQueue
实现有界的优先队列。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| import java.util.*;
public class BoundedPriorityQueue<E> extends PriorityQueue<E> {
private static final long serialVersionUID = 3794348988671694820L;
private int capacity;
private Comparator<? super E> comparator;
public BoundedPriorityQueue(int capacity) { this(capacity, null); }
public BoundedPriorityQueue(int capacity, final Comparator<? super E> comparator) { super(capacity, (o1, o2) -> { int cResult; if (comparator != null) { cResult = comparator.compare(o1, o2); } else { @SuppressWarnings("unchecked") Comparable<E> o1c = (Comparable<E>) o1; cResult = o1c.compareTo(o2); }
return -cResult; }); this.capacity = capacity; this.comparator = comparator; }
@Override public boolean offer(E e) { if (size() >= capacity) { E head = peek(); if (this.comparator().compare(e, head) <= 0) { return true; } poll(); } return super.offer(e); }
public boolean addAll(E[] c) { return this.addAll(Arrays.asList(c)); }
public ArrayList<E> toList() { final ArrayList<E> list = new ArrayList<>(this); list.sort(comparator); return list; }
@Override public Iterator<E> iterator() { return toList().iterator(); } }
|