常量
private static final int DEFAULT_INITIAL_CAPACITY = 11;
transient Object[] queue;
private int size = 0;
private final Comparator<? super E> comparator;
transient int modCount = 0;
插入操作 add()
public boolean add(E e) {
return offer(e);
}
public boolean offer(E e) {
if (e == null)
throw new NullPointerException();
modCount++;
int i = size;
if (i >= queue.length)
grow(i + 1);
size = i + 1;
if (i == 0)
queue[0] = e;
else
siftUp(i, e);
return true;
}
private void siftUp(int k, E x) {
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
}
@SuppressWarnings("unchecked")
private void siftUpComparable(int k, E x) {
Comparable<? super E> key = (Comparable<? super E>) x;
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = queue[parent];
if (key.compareTo((E) e) >= 0)
break;
queue[k] = e;
k = parent;
}
queue[k] = key;
}
@SuppressWarnings("unchecked")
private void siftUpUsingComparator(int k, E x) {
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = queue[parent];
if (comparator.compare(x, (E) e) >= 0)
break;
queue[k] = e;
k = parent;
}
queue[k] = x;
}
poll() 获取并删除
@SuppressWarnings("unchecked")
public E poll() {
if (size == 0)
return null;
int s = --size;
modCount++;
E result = (E) queue[0];
E x = (E) queue[s];
queue[s] = null;
if (s != 0)
siftDown(0, x);
return result;
}
private void siftDown(int k, E x) {
if (comparator != null)
siftDownUsingComparator(k, x);
else
siftDownComparable(k, x);
}
@SuppressWarnings("unchecked")
private void siftDownUsingComparator(int k, E x) {
int half = size >>> 1;
while (k < half) {
int child = (k << 1) + 1;
Object c = queue[child];
int right = child + 1;
if (right < size &&
comparator.compare((E) c, (E) queue[right]) > 0)
c = queue[child = right];
if (comparator.compare(x, (E) c) <= 0)
break;
queue[k] = c;
k = child;
}
queue[k] = x;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7b43de9d925fbc13e503868200191129.png)
实例
import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
public class MyPriorityQueue {
public static void main(String[] args) {
PriorityQueue<Integer> q = new PriorityQueue<>(7);
q.add(5);
q.add(33);
q.add(4);
Iterator iterator = q.iterator();
while(iterator.hasNext()) {
System.out.println(q.poll());
}
PriorityQueue<Demo> pq = new PriorityQueue<Demo>(7,new Demo());
pq.add(new Demo(5,"s1"));
pq.add(new Demo(33,"s2"));
pq.add(new Demo(51,"s3"));
pq.add(new Demo(15,"s4"));
Iterator iteratorq = pq.iterator();
while(iteratorq.hasNext()) {
System.out.println(pq.poll().getAge());
}
}
static class Demo implements Comparator<Demo>{
private int age;
private String name;
public Demo() {
}
public Demo(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compare(Demo o1, Demo o2) {
return o2.age - o1.age;
}
}
}