1 package org.apache.lucene.search;
4 * Licensed to the Apache Software Foundation (ASF) under one or more
5 * contributor license agreements. See the NOTICE file distributed with
6 * this work for additional information regarding copyright ownership.
7 * The ASF licenses this file to You under the Apache License, Version 2.0
8 * (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
20 import org.apache.lucene.util.PriorityQueue;
22 final class HitQueue extends PriorityQueue<ScoreDoc> {
24 private boolean prePopulate;
27 * Creates a new instance with <code>size</code> elements. If
28 * <code>prePopulate</code> is set to true, the queue will pre-populate itself
29 * with sentinel objects and set its {@link #size()} to <code>size</code>. In
30 * that case, you should not rely on {@link #size()} to get the number of
31 * actual elements that were added to the queue, but keep track yourself.<br>
32 * <b>NOTE:</b> in case <code>prePopulate</code> is true, you should pop
33 * elements from the queue using the following code example:
36 * PriorityQueue pq = new HitQueue(10, true); // pre-populate.
37 * ScoreDoc top = pq.top();
39 * // Add/Update one element.
42 * top = (ScoreDoc) pq.updateTop();
45 * // Now pop only the elements that were *truly* inserted.
46 * // First, pop all the sentinel elements (there are pq.size() - totalHits).
47 * for (int i = pq.size() - totalHits; i > 0; i--) pq.pop();
49 * // Now pop the truly added elements.
50 * ScoreDoc[] results = new ScoreDoc[totalHits];
51 * for (int i = totalHits - 1; i >= 0; i--) {
52 * results[i] = (ScoreDoc) pq.pop();
56 * <p><b>NOTE</b>: This class pre-allocate a full array of
57 * length <code>size</code>.
60 * the requested size of this queue.
62 * specifies whether to pre-populate the queue with sentinel values.
63 * @see #getSentinelObject()
65 HitQueue(int size, boolean prePopulate) {
66 this.prePopulate = prePopulate;
70 // Returns null if prePopulate is false.
72 protected ScoreDoc getSentinelObject() {
73 // Always set the doc Id to MAX_VALUE so that it won't be favored by
74 // lessThan. This generally should not happen since if score is not NEG_INF,
75 // TopScoreDocCollector will always add the object to the queue.
76 return !prePopulate ? null : new ScoreDoc(Integer.MAX_VALUE, Float.NEGATIVE_INFINITY);
80 protected final boolean lessThan(ScoreDoc hitA, ScoreDoc hitB) {
81 if (hitA.score == hitB.score)
82 return hitA.doc > hitB.doc;
84 return hitA.score < hitB.score;