赞
踩
PriorityQueue中Comparator的用法首先先看源码中的offer:
- 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;
- }
1)if和else,分别执行对象判空和容量判断
2)执行siftUp(i, e),i是原有队列长度,e是要入队的元素。
- private void siftUp(int k, E x) {
- if (comparator != null)
- siftUpUsingComparator(k, x);
- else
- siftUpComparable(k, x);
- }
siftUp是堆中调整元素位置的一种方法,可以看出这里的优先队列是使用最大/最小堆实现的。
观察comparator不为空的情况:
k是原有队列长度,x是要入队的元素,e是父节点(也是最后一个非叶子结点)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。