forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PriorityQueue.java
1345 lines (1122 loc) · 52.1 KB
/
PriorityQueue.java
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
import java.io.IOException;
import java.io.Serializable;
import java.util.function.Consumer;
import java.util.function.Predicate;
import jdk.internal.misc.SharedSecrets;
/**
* An unbounded priority {@linkplain Queue queue} based on a priority heap.
* The elements of the priority queue are ordered according to their
* {@linkplain Comparable natural ordering}, or by a {@link Comparator}
* provided at queue construction time, depending on which constructor is
* used. A priority queue does not permit {@code null} elements.
* A priority queue relying on natural ordering also does not permit
* insertion of non-comparable objects (doing so may result in
* {@code ClassCastException}).
*
* <p>The <em>head</em> of this queue is the <em>least</em> element
* with respect to the specified ordering. If multiple elements are
* tied for least value, the head is one of those elements -- ties are
* broken arbitrarily. The queue retrieval operations {@code poll},
* {@code remove}, {@code peek}, and {@code element} access the
* element at the head of the queue.
*
* <p>A priority queue is unbounded, but has an internal
* <i>capacity</i> governing the size of an array used to store the
* elements on the queue. It is always at least as large as the queue
* size. As elements are added to a priority queue, its capacity
* grows automatically. The details of the growth policy are not
* specified.
*
* <p>This class and its iterator implement all of the
* <em>optional</em> methods of the {@link Collection} and {@link
* Iterator} interfaces. The Iterator provided in method {@link
* #iterator()} and the Spliterator provided in method {@link #spliterator()}
* are <em>not</em> guaranteed to traverse the elements of
* the priority queue in any particular order. If you need ordered
* traversal, consider using {@code Arrays.sort(pq.toArray())}.
*
* <p><strong>Note that this implementation is not synchronized.</strong>
* Multiple threads should not access a {@code PriorityQueue}
* instance concurrently if any of the threads modifies the queue.
* Instead, use the thread-safe {@link
* java.util.concurrent.PriorityBlockingQueue} class.
*
* <p>Implementation note: this implementation provides
* O(log(n)) time for the enqueuing and dequeuing methods
* ({@code offer}, {@code poll}, {@code remove()} and {@code add});
* linear time for the {@code remove(Object)} and {@code contains(Object)}
* methods; and constant time for the retrieval methods
* ({@code peek}, {@code element}, and {@code size}).
*
* <p>This class is a member of the
* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
* Java Collections Framework</a>.
*
* @param <E> the type of elements held in this queue
*
* @author Josh Bloch, Doug Lea
* @since 1.5
*/
/*
* 顺序无界(队列容量支持扩容到Integer.MAX_VALUE)优先队列,非线程安全
*
* 该容器的内部实现为【小顶堆】
*
* 一般要求优先队列容器支持外部比较器,如果该容器不支持外部比较器,
* 则强制要求优先队列内的元素实现内部比较器接口。
* 这是因为容器中的元素是根据"优先级"来放置的,
* 而确定"优先级"的方式就是使用比较器。
*/
@SuppressWarnings("unchecked")
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable {
// 优先队列的默认初始容量
private static final int DEFAULT_INITIAL_CAPACITY = 11;
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* The comparator, or null if priority queue uses elements'
* natural ordering.
*/
// 外部比较器,支持以自定义的顺序来比较元素。如果没有设置,则使用元素自身实现的内部比较器
private final Comparator<? super E> comparator;
/**
* Priority queue represented as a balanced binary heap: the two
* children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The
* priority queue is ordered by comparator, or by the elements'
* natural ordering, if comparator is null: For each node n in the
* heap and each descendant d of n, n <= d. The element with the
* lowest value is in queue[0], assuming the queue is nonempty.
*/
// 存储队列元素
transient Object[] queue; // non-private to simplify nested class access
/**
* The number of elements in the priority queue.
*/
// 队列长度
int size;
/**
* The number of times this priority queue has been
* <i>structurally modified</i>. See AbstractList for gory details.
*/
// 记录队列结构的变动次数
transient int modCount; // non-private to simplify nested class access
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a {@code PriorityQueue} with the default initial
* capacity (11) that orders its elements according to their
* {@linkplain Comparable natural ordering}.
*/
public PriorityQueue() {
this(DEFAULT_INITIAL_CAPACITY, null);
}
/**
* Creates a {@code PriorityQueue} with the specified initial
* capacity that orders its elements according to their
* {@linkplain Comparable natural ordering}.
*
* @param initialCapacity the initial capacity for this priority queue
*
* @throws IllegalArgumentException if {@code initialCapacity} is less
* than 1
*/
public PriorityQueue(int initialCapacity) {
this(initialCapacity, null);
}
/**
* Creates a {@code PriorityQueue} with the default initial capacity and
* whose elements are ordered according to the specified comparator.
*
* @param comparator the comparator that will be used to order this
* priority queue. If {@code null}, the {@linkplain Comparable
* natural ordering} of the elements will be used.
*
* @since 1.8
*/
public PriorityQueue(Comparator<? super E> comparator) {
this(DEFAULT_INITIAL_CAPACITY, comparator);
}
/**
* Creates a {@code PriorityQueue} with the specified initial capacity
* that orders its elements according to the specified comparator.
*
* @param initialCapacity the initial capacity for this priority queue
* @param comparator the comparator that will be used to order this
* priority queue. If {@code null}, the {@linkplain Comparable
* natural ordering} of the elements will be used.
*
* @throws IllegalArgumentException if {@code initialCapacity} is
* less than 1
*/
public PriorityQueue(int initialCapacity, Comparator<? super E> comparator) {
// Note: This restriction of at least one is not actually needed, but continues for 1.5 compatibility
if(initialCapacity<1) {
throw new IllegalArgumentException();
}
this.queue = new Object[initialCapacity];
this.comparator = comparator;
}
/**
* Creates a {@code PriorityQueue} containing the elements in the
* specified priority queue. This priority queue will be
* ordered according to the same ordering as the given priority
* queue.
*
* @param c the priority queue whose elements are to be placed
* into this priority queue
*
* @throws ClassCastException if elements of {@code c} cannot be
* compared to one another according to {@code c}'s
* ordering
* @throws NullPointerException if the specified priority queue or any
* of its elements are null
*/
public PriorityQueue(PriorityQueue<? extends E> c) {
this.comparator = (Comparator<? super E>) c.comparator();
// 用指定的优先队列中的元素初始化当前优先队列
initFromPriorityQueue(c);
}
/**
* Creates a {@code PriorityQueue} containing the elements in the
* specified sorted set. This priority queue will be ordered
* according to the same ordering as the given sorted set.
*
* @param c the sorted set whose elements are to be placed
* into this priority queue
*
* @throws ClassCastException if elements of the specified sorted
* set cannot be compared to one another according to the
* sorted set's ordering
* @throws NullPointerException if the specified sorted set or any
* of its elements are null
*/
public PriorityQueue(SortedSet<? extends E> c) {
this.comparator = (Comparator<? super E>) c.comparator();
// 用指定容器中的元素初始化优先队列
initElementsFromCollection(c);
}
/**
* Creates a {@code PriorityQueue} containing the elements in the
* specified collection. If the specified collection is an instance of
* a {@link SortedSet} or is another {@code PriorityQueue}, this
* priority queue will be ordered according to the same ordering.
* Otherwise, this priority queue will be ordered according to the
* {@linkplain Comparable natural ordering} of its elements.
*
* @param c the collection whose elements are to be placed
* into this priority queue
*
* @throws ClassCastException if elements of the specified collection
* cannot be compared to one another according to the priority
* queue's ordering
* @throws NullPointerException if the specified collection or any
* of its elements are null
*/
public PriorityQueue(Collection<? extends E> c) {
if(c instanceof SortedSet<?>) {
SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
this.comparator = (Comparator<? super E>) ss.comparator();
// 用指定容器中的元素初始化优先队列
initElementsFromCollection(ss);
} else if(c instanceof PriorityQueue<?>) {
PriorityQueue<? extends E> pq = (PriorityQueue<? extends E>) c;
this.comparator = (Comparator<? super E>) pq.comparator();
// 用指定的优先队列中的元素初始化当前优先队列
initFromPriorityQueue(pq);
} else {
this.comparator = null;
// 用指定容器中的元素初始化优先队列,并重建小顶堆
initFromCollection(c);
}
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 入队 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Inserts the specified element into this priority queue.
*
* @return {@code true} (as specified by {@link Queue#offer})
*
* @throws ClassCastException if the specified element cannot be
* compared with elements currently in this priority queue
* according to the priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
// 入队,非线程安全,无法入队时扩容
public boolean offer(E e) {
if(e == null) {
throw new NullPointerException();
}
modCount++;
int i = size;
if(i >= queue.length) {
grow(i + 1);
}
// 插入。需要从小顶堆的结点i开始,向【上】查找一个合适的位置插入x
siftUp(i, e);
// 队列长度增一
size = i + 1;
return true;
}
/**
* Inserts the specified element into this priority queue.
*
* @return {@code true} (as specified by {@link Collection#add})
*
* @throws ClassCastException if the specified element cannot be
* compared with elements currently in this priority queue
* according to the priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
// 入队/添加,非线程安全。无法入队时扩容
public boolean add(E e) {
return offer(e);
}
/*▲ 入队 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 出队 ████████████████████████████████████████████████████████████████████████████████┓ */
// 出队,非线程安全,无法出队时返回null
public E poll() {
final Object[] es = queue;
// 获取队头元素
final E result = (E)es[0];
// 如果队头元素不为空
if(result!= null) {
modCount++;
final int n = --size;
// 摘下队尾元素
final E x = (E) es[n];
es[n] = null;
// 插入。需要从小顶堆的根结点开始,向【下】查找一个合适的位置插入队尾元素
if(n>0) {
final Comparator<? super E> cmp;
if((cmp = comparator) == null) {
siftDownComparable(0, x, es, n);
} else {
siftDownUsingComparator(0, x, es, n, cmp);
}
}
}
return result;
}
/**
* Removes a single instance of the specified element from this queue,
* if it is present. More formally, removes an element {@code e} such
* that {@code o.equals(e)}, if this queue contains one or more such
* elements. Returns {@code true} if and only if this queue contained
* the specified element (or equivalently, if this queue changed as a
* result of the call).
*
* @param o element to be removed from this queue, if present
*
* @return {@code true} if this queue changed as a result of the call
*/
// 移除,非线程安全,移除成功则返回true
public boolean remove(Object o) {
// 获取指定元素在队列中的索引,不在队列中时返回-1
int i = indexOf(o);
// 如果元素不在队列中,返回false
if(i == -1) {
return false;
}
// 移除队列索引i处的元素。如果小顶堆中的元素顺序发生了改变,则返回队尾元素
removeAt(i);
return true;
}
/**
* Removes the ith element from queue.
*
* Normally this method leaves the elements at up to i-1,
* inclusive, untouched. Under these circumstances, it returns
* null. Occasionally, in order to maintain the heap invariant,
* it must swap a later element of the list with one earlier than
* i. Under these circumstances, this method returns the element
* that was previously at the end of the list and is now at some
* position before i. This fact is used by iterator.remove so as to
* avoid missing traversing elements.
*/
// 移除队列索引i处的元素。如果小顶堆中的元素顺序发生了改变,则返回队尾元素
E removeAt(int i) {
// assert i >= 0 && i < size;
final Object[] es = queue;
modCount++;
int s = --size;
// 如果移除的是队尾元素
if(s == i) {
// removed last element
es[i] = null;
} else {
/* 如果不是移除队尾元素,则需要将队尾元素防止在新的小顶堆中的合适位置 */
// 摘下队尾元素
E moved = (E) es[s];
es[s] = null;
// 插入。需要从小顶堆的结点i开始,向【下】查找一个合适的位置插入moved
siftDown(i, moved);
/*
* 如果待moved是以i为根结点的小顶堆上的最小值,
* 那么不能保证moved比结点i的父结点元素更大,
* 此时需要向上搜寻moved的一个合适的插入位置
*/
if(es[i] == moved) {
// 插入。需要从小顶堆的结点i开始,向【上】查找一个合适的位置插入moved
siftUp(i, moved);
/*
* 如果i处的新元素不是队尾元素,
* 说明小顶堆中的元素顺序发生了改变(不考虑i处的变化),
* 此时返回队尾元素
*/
if(es[i] != moved) {
return moved;
}
}
}
return null;
}
/**
* @throws NullPointerException {@inheritDoc}
*/
// 移除所有满足过滤条件的元素(非线程安全)
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
return bulkRemove(filter);
}
/**
* @throws NullPointerException {@inheritDoc}
*/
// (匹配则移除)移除队列中所有与给定容器中的元素匹配的元素(非线程安全)
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return bulkRemove(e -> c.contains(e));
}
/**
* @throws NullPointerException {@inheritDoc}
*/
// (不匹配则移除)移除队列中所有与给定容器中的元素不匹配的元素(非线程安全)
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return bulkRemove(e -> !c.contains(e));
}
/**
* Removes all of the elements from this priority queue.
* The queue will be empty after this call returns.
*/
// 清空,即移除所有元素(非线程安全)
public void clear() {
modCount++;
final Object[] es = queue;
for(int i = 0, n = size; i<n; i++) {
es[i] = null;
}
size = 0;
}
/*▲ 出队 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 取值 ████████████████████████████████████████████████████████████████████████████████┓ */
// 获取队头元素
public E peek() {
return (E) queue[0];
}
/*▲ 取值 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 包含查询 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns {@code true} if this queue contains the specified element.
* More formally, returns {@code true} if and only if this queue contains
* at least one element {@code e} such that {@code o.equals(e)}.
*
* @param o object to be checked for containment in this queue
*
* @return {@code true} if this queue contains the specified element
*/
// 判断队列中是否包含元素o
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/*▲ 包含查询 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 视图 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns an array containing all of the elements in this queue.
* The elements are in no particular order.
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this queue. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this queue
*/
public Object[] toArray() {
return Arrays.copyOf(queue, size);
}
/**
* Returns an array containing all of the elements in this queue; the
* runtime type of the returned array is that of the specified array.
* The returned array elements are in no particular order.
* If the queue fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of this queue.
*
* <p>If the queue fits in the specified array with room to spare
* (i.e., the array has more elements than the queue), the element in
* the array immediately following the end of the collection is set to
* {@code null}.
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose {@code x} is a queue known to contain only strings.
* The following code can be used to dump the queue into a newly
* allocated array of {@code String}:
*
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
*
* @param a the array into which the elements of the queue are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
*
* @return an array containing all of the elements in this queue
*
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this queue
* @throws NullPointerException if the specified array is null
*/
public <T> T[] toArray(T[] a) {
final int size = this.size;
if(a.length<size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(queue, size, a.getClass());
System.arraycopy(queue, 0, a, 0, size);
if(a.length>size)
a[size] = null;
return a;
}
/*▲ 视图 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 迭代 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* @throws NullPointerException {@inheritDoc}
*/
// 遍历所有元素,并执行相应的择取操作
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
final Object[] es = queue;
for(int i = 0, n = size; i<n; i++) {
action.accept((E) es[i]);
}
if(expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
}
/**
* Returns an iterator over the elements in this queue. The iterator
* does not return the elements in any particular order.
*
* @return an iterator over the elements in this queue
*/
// 返回当前队列的迭代器
public Iterator<E> iterator() {
return new Itr();
}
/**
* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
* and <em>fail-fast</em> {@link Spliterator} over the elements in this
* queue. The spliterator does not traverse elements in any particular order
* (the {@link Spliterator#ORDERED ORDERED} characteristic is not reported).
*
* <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
* {@link Spliterator#SUBSIZED}, and {@link Spliterator#NONNULL}.
* Overriding implementations should document the reporting of additional
* characteristic values.
*
* @return a {@code Spliterator} over the elements in this queue
*
* @since 1.8
*/
// 返回描述此队列中元素的Spliterator
public final Spliterator<E> spliterator() {
return new PriorityQueueSpliterator(0, -1, 0);
}
/*▲ 迭代 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 杂项 ████████████████████████████████████████████████████████████████████████████████┓ */
// 返回队列中元素数量
public int size() {
return size;
}
/**
* Returns the comparator used to order the elements in this
* queue, or {@code null} if this queue is sorted according to
* the {@linkplain Comparable natural ordering} of its elements.
*
* @return the comparator used to order this queue, or
* {@code null} if this queue is sorted according to the
* natural ordering of its elements
*/
// 返回该队列使用的外部比较器
public Comparator<? super E> comparator() {
return comparator;
}
/*▲ 杂项 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 序列化 ████████████████████████████████████████████████████████████████████████████████┓ */
private static final long serialVersionUID = -7720805057305804111L;
/**
* Saves this queue to a stream (that is, serializes it).
*
* @param s the stream
*
* @throws java.io.IOException if an I/O error occurs
* @serialData The length of the array backing the instance is
* emitted (int), followed by all of its elements
* (each an {@code Object}) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
// Write out element count, and any hidden stuff
s.defaultWriteObject();
// Write out array length, for compatibility with 1.5 version
s.writeInt(Math.max(2, size + 1));
// Write out all elements in the "proper order".
final Object[] es = queue;
for(int i = 0, n = size; i<n; i++)
s.writeObject(es[i]);
}
/**
* Reconstitutes the {@code PriorityQueue} instance from a stream
* (that is, deserializes it).
*
* @param s the stream
*
* @throws ClassNotFoundException if the class of a serialized object
* could not be found
* @throws java.io.IOException if an I/O error occurs
*/
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in (and discard) array length
s.readInt();
SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);
final Object[] es = queue = new Object[Math.max(size, 1)];
// Read in all elements.
for(int i = 0, n = size; i<n; i++)
es[i] = s.readObject();
// Elements are guaranteed to be in "proper order", but the
// spec has never explained what that might be.
heapify();
}
/*▲ 序列化 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 初始化 ████████████████████████████████████████████████████████████████████████████████┓ */
// 用指定的优先队列中的元素初始化当前优先队列
private void initFromPriorityQueue(PriorityQueue<? extends E> c) {
if(c.getClass() == PriorityQueue.class) {
this.queue = ensureNonEmpty(c.toArray());
this.size = c.size();
} else {
// 用指定容器中的元素初始化优先队列,并重建小顶堆
initFromCollection(c);
}
}
/**
* Initializes queue array with elements from the given Collection.
*
* @param c the collection
*/
// 用指定容器中的元素初始化优先队列,并重建小顶堆
private void initFromCollection(Collection<? extends E> c) {
// 用指定容器中的元素初始化优先队列
initElementsFromCollection(c);
// 重建小顶堆
heapify();
}
// 用指定容器中的元素初始化优先队列
private void initElementsFromCollection(Collection<? extends E> c) {
// 获取容器中的元素
Object[] es = c.toArray();
int len = es.length;
// If c.toArray incorrectly doesn't return Object[], copy it.
if(es.getClass() != Object[].class) {
es = Arrays.copyOf(es, len, Object[].class);
}
// 确保优先队列中的元素不为空
if(len == 1 || this.comparator != null) {
for(Object e : es) {
if(e == null) {
throw new NullPointerException();
}
}
}
this.queue = ensureNonEmpty(es);
this.size = len;
}
/** Ensures that queue[0] exists, helping peek() and poll(). */
// 确保返回的数组长度>=1
private static Object[] ensureNonEmpty(Object[] es) {
return (es.length>0) ? es : new Object[1];
}
/*▲ 初始化 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 小顶堆 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Inserts item x at position k, maintaining heap invariant by
* promoting x up the tree until it is greater than or equal to
* its parent, or is the root.
*
* To simplify and speed up coercions and comparisons, the
* Comparable and Comparator versions are separated into different
* methods that are otherwise identical. (Similarly for siftDown.)
*
* @param i the position to fill
* @param x the item to insert
*/
// 插入。需要从小顶堆的结点i开始,向【上】查找一个合适的位置插入x
private void siftUp(int i, E x) {
if(comparator == null) {
siftUpComparable(i, x, queue);
} else {
siftUpUsingComparator(i, x, queue, comparator);
}
}
/**
* Inserts item x at position k, maintaining heap invariant by
* demoting x down the tree repeatedly until it is less than or
* equal to its children or is a leaf.
*
* @param i the position to fill
* @param x the item to insert
*/
// 插入。需要从小顶堆的结点i开始,向【下】查找一个合适的位置插入x
private void siftDown(int i, E x) {
if(comparator == null) {
siftDownComparable(i, x, queue, size);
} else {
siftDownUsingComparator(i, x, queue, size, comparator);
}
}
// 插入。需要从小顶堆的结点i开始,向上查找一个合适的位置插入x
private static <T> void siftUpComparable(int i, T x, Object[] es) {
// 类型转换,要求待插入元素必须实现Comparable接口
Comparable<? super T> key = (Comparable<? super T>) x;
while(i>0) {
// 获取父结点索引
int parent = (i - 1) >>> 1;
// 父结点
Object e = es[parent];
// 如果待插入元素大于父节点中的元素,则退出循环
if(key.compareTo((T) e) >= 0) {
break;
}
// 子结点保存父结点中的元素
es[i] = e;
// 向上搜寻合适的插入位置
i = parent;
}
// 将元素key插入到合适的位置
es[i] = key;
}
// 插入。需要从小顶堆的结点i开始,向上查找一个合适的位置插入x
private static <T> void siftUpUsingComparator(int i, T x, Object[] es, Comparator<? super T> cmp) {
while(i>0) {
// 获取父结点索引
int parent = (i - 1) >>> 1;
// 父结点
Object e = es[parent];
// 如果待插入元素大于父节点中的元素,则退出循环
if(cmp.compare(x, (T) e) >= 0) {
break;
}
// 子结点保存父结点中的元素
es[i] = e;
// 向上搜寻合适的插入位置
i = parent;
}
// 将元素x插入到合适的位置
es[i] = x;
}
// 插入。需要从小顶堆的结点i开始,向下查找一个合适的位置插入x
private static <T> void siftDownComparable(int i, T x, Object[] es, int n) {
// 类型转换,要求待插入元素必须实现Comparable接口
Comparable<? super T> key = (Comparable<? super T>) x;
// 最多搜索一半元素
int half = n >>> 1; // loop while a non-leaf
while(i<half) {
int min = (i << 1) + 1; // 左结点索引
int right = min + 1; // 右结点索引
// 假设左结点为较小的结点
Object c = es[min];
// 如果右结点更小
if(right<n && ((Comparable<? super T>) c).compareTo((T) es[right])>0) {
// 更新min指向子结点中较小的结点
c = es[min = right];
}
// 如果待插入元素小于子结点中较小的元素,则退出循环
if(key.compareTo((T) c)<=0) {
break;
}
// 父结点位置保存子结点中较小的元素
es[i] = c;
// 向下搜寻合适的插入位置
i = min;
}
// 将元素key插入到合适的位置
es[i] = key;
}
// 插入。需要从小顶堆的结点i开始,向下查找一个合适的位置插入x
private static <T> void siftDownUsingComparator(int i, T x, Object[] es, int n, Comparator<? super T> cmp) {
// 最多搜索一半元素
int half = n >>> 1;
while(i<half) {
int min = (i << 1) + 1; // 左结点索引
int right = min + 1; // 右结点索引
// 假设左结点为较小的结点
Object c = es[min];
// 如果右结点更小
if(right<n && cmp.compare((T) c, (T) es[right])>0) {
// 更新min指向子结点中较小的结点
c = es[min = right];
}
// 如果待插入元素小于子结点中较小的元素,则退出循环
if(cmp.compare(x, (T) c)<=0) {
break;
}
// 父结点位置保存子结点中较小的元素
es[i] = c;
// 向下搜寻合适的插入位置
i = min;
}
// 将元素x插入到合适的位置
es[i] = x;
}
/**
* Establishes the heap invariant (described above) in the entire tree,
* assuming nothing about the order of the elements prior to the call.
* This classic algorithm due to Floyd (1964) is known to be O(size).
*/
// 重建小顶堆
private void heapify() {
final Object[] es = queue;
int n = size;
// 从中间开始,倒着往回遍历
int i = (n >>> 1) - 1;
final Comparator<? super E> cmp;
/* 插入。需要从小顶堆的结点i开始,向【下】查找一个合适的位置插入es[i] */
if((cmp = comparator) == null) {
for(; i >= 0; i--) {
siftDownComparable(i, es[i], es, n);
}
} else {