001 /*
002 * Copyright (C) 2007 Google Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package com.google.common.collect;
018
019 import static com.google.common.base.Preconditions.checkArgument;
020 import static com.google.common.base.Preconditions.checkNotNull;
021
022 import com.google.common.annotations.Beta;
023 import com.google.common.annotations.GwtCompatible;
024 import com.google.common.annotations.VisibleForTesting;
025 import com.google.common.base.Function;
026
027 import java.util.Arrays;
028 import java.util.Collections;
029 import java.util.Comparator;
030 import java.util.HashSet;
031 import java.util.Iterator;
032 import java.util.List;
033 import java.util.Map;
034 import java.util.NoSuchElementException;
035 import java.util.SortedMap;
036 import java.util.SortedSet;
037 import java.util.concurrent.atomic.AtomicInteger;
038
039 import javax.annotation.Nullable;
040
041 /**
042 * A comparator with added methods to support common functions. For example:
043 * <pre> {@code
044 *
045 * if (Ordering.from(comparator).reverse().isOrdered(list)) { ... }}</pre>
046 *
047 * The {@link #from(Comparator)} method returns the equivalent {@code Ordering}
048 * instance for a pre-existing comparator. You can also skip the comparator step
049 * and extend {@code Ordering} directly: <pre> {@code
050 *
051 * Ordering<String> byLengthOrdering = new Ordering<String>() {
052 * public int compare(String left, String right) {
053 * return Ints.compare(left.length(), right.length());
054 * }
055 * };}</pre>
056 *
057 * Except as noted, the orderings returned by the factory methods of this
058 * class are serializable if and only if the provided instances that back them
059 * are. For example, if {@code ordering} and {@code function} can themselves be
060 * serialized, then {@code ordering.onResultOf(function)} can as well.
061 *
062 * @author Jesse Wilson
063 * @author Kevin Bourrillion
064 * @since 2 (imported from Google Collections Library)
065 */
066 @GwtCompatible
067 public abstract class Ordering<T> implements Comparator<T> {
068 // Static factories
069
070 /**
071 * Returns a serializable ordering that uses the natural order of the values.
072 * The ordering throws a {@link NullPointerException} when passed a null
073 * parameter.
074 *
075 * <p>The type specification is {@code <C extends Comparable>}, instead of
076 * the technically correct {@code <C extends Comparable<? super C>>}, to
077 * support legacy types from before Java 5.
078 */
079 @GwtCompatible(serializable = true)
080 @SuppressWarnings("unchecked") // TODO(kevinb): the right way to explain this??
081 public static <C extends Comparable> Ordering<C> natural() {
082 return (Ordering) NaturalOrdering.INSTANCE;
083 }
084
085 /**
086 * Returns an ordering for a pre-existing {@code comparator}. Note
087 * that if the comparator is not pre-existing, and you don't require
088 * serialization, you can subclass {@code Ordering} and implement its
089 * {@link #compare(Object, Object) compare} method instead.
090 *
091 * @param comparator the comparator that defines the order
092 */
093 @GwtCompatible(serializable = true)
094 public static <T> Ordering<T> from(Comparator<T> comparator) {
095 return (comparator instanceof Ordering)
096 ? (Ordering<T>) comparator
097 : new ComparatorOrdering<T>(comparator);
098 }
099
100 /**
101 * Simply returns its argument.
102 *
103 * @deprecated no need to use this
104 */
105 @GwtCompatible(serializable = true)
106 @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering) {
107 return checkNotNull(ordering);
108 }
109
110 /**
111 * Returns an ordering that compares objects according to the order in
112 * which they appear in the given list. Only objects present in the list
113 * (according to {@link Object#equals}) may be compared. This comparator
114 * imposes a "partial ordering" over the type {@code T}. Subsequent changes
115 * to the {@code valuesInOrder} list will have no effect on the returned
116 * comparator. Null values in the list are not supported.
117 *
118 * <p>The returned comparator throws an {@link ClassCastException} when it
119 * receives an input parameter that isn't among the provided values.
120 *
121 * <p>The generated comparator is serializable if all the provided values are
122 * serializable.
123 *
124 * @param valuesInOrder the values that the returned comparator will be able
125 * to compare, in the order the comparator should induce
126 * @return the comparator described above
127 * @throws NullPointerException if any of the provided values is null
128 * @throws IllegalArgumentException if {@code valuesInOrder} contains any
129 * duplicate values (according to {@link Object#equals})
130 */
131 @GwtCompatible(serializable = true)
132 public static <T> Ordering<T> explicit(List<T> valuesInOrder) {
133 return new ExplicitOrdering<T>(valuesInOrder);
134 }
135
136 /**
137 * Returns an ordering that compares objects according to the order in
138 * which they are given to this method. Only objects present in the argument
139 * list (according to {@link Object#equals}) may be compared. This comparator
140 * imposes a "partial ordering" over the type {@code T}. Null values in the
141 * argument list are not supported.
142 *
143 * <p>The returned comparator throws a {@link ClassCastException} when it
144 * receives an input parameter that isn't among the provided values.
145 *
146 * <p>The generated comparator is serializable if all the provided values are
147 * serializable.
148 *
149 * @param leastValue the value which the returned comparator should consider
150 * the "least" of all values
151 * @param remainingValuesInOrder the rest of the values that the returned
152 * comparator will be able to compare, in the order the comparator should
153 * follow
154 * @return the comparator described above
155 * @throws NullPointerException if any of the provided values is null
156 * @throws IllegalArgumentException if any duplicate values (according to
157 * {@link Object#equals(Object)}) are present among the method arguments
158 */
159 @GwtCompatible(serializable = true)
160 public static <T> Ordering<T> explicit(
161 T leastValue, T... remainingValuesInOrder) {
162 return explicit(Lists.asList(leastValue, remainingValuesInOrder));
163 }
164
165 /**
166 * Exception thrown by a {@link Ordering#explicit(List)} or {@link
167 * Ordering#explicit(Object, Object[])} comparator when comparing a value
168 * outside the set of values it can compare. Extending {@link
169 * ClassCastException} may seem odd, but it is required.
170 */
171 // TODO(kevinb): make this public, document it right
172 @VisibleForTesting
173 static class IncomparableValueException extends ClassCastException {
174 final Object value;
175
176 IncomparableValueException(Object value) {
177 super("Cannot compare value: " + value);
178 this.value = value;
179 }
180
181 private static final long serialVersionUID = 0;
182 }
183
184 /**
185 * Returns an arbitrary ordering over all objects, for which {@code compare(a,
186 * b) == 0} implies {@code a == b} (identity equality). There is no meaning
187 * whatsoever to the order imposed, but it is constant for the life of the VM.
188 *
189 * <p>Because the ordering is identity-based, it is not "consistent with
190 * {@link Object#equals(Object)}" as defined by {@link Comparator}. Use
191 * caution when building a {@link SortedSet} or {@link SortedMap} from it, as
192 * the resulting collection will not behave exactly according to spec.
193 *
194 * <p>This ordering is not serializable, as its implementation relies on
195 * {@link System#identityHashCode(Object)}, so its behavior cannot be
196 * preserved across serialization.
197 *
198 * @since 2
199 */
200 public static Ordering<Object> arbitrary() {
201 return ArbitraryOrderingHolder.ARBITRARY_ORDERING;
202 }
203
204 private static class ArbitraryOrderingHolder {
205 static final Ordering<Object> ARBITRARY_ORDERING = new ArbitraryOrdering();
206 }
207
208 @VisibleForTesting static class ArbitraryOrdering extends Ordering<Object> {
209 private Map<Object, Integer> uids =
210 Platform.tryWeakKeys(new MapMaker()).makeComputingMap(
211 new Function<Object, Integer>() {
212 final AtomicInteger counter = new AtomicInteger(0);
213 public Integer apply(Object from) {
214 return counter.getAndIncrement();
215 }
216 });
217
218 @Override public int compare(Object left, Object right) {
219 if (left == right) {
220 return 0;
221 }
222 int leftCode = identityHashCode(left);
223 int rightCode = identityHashCode(right);
224 if (leftCode != rightCode) {
225 return leftCode < rightCode ? -1 : 1;
226 }
227
228 // identityHashCode collision (rare, but not as rare as you'd think)
229 int result = uids.get(left).compareTo(uids.get(right));
230 if (result == 0) {
231 throw new AssertionError(); // extremely, extremely unlikely.
232 }
233 return result;
234 }
235
236 @Override public String toString() {
237 return "Ordering.arbitrary()";
238 }
239
240 /*
241 * We need to be able to mock identityHashCode() calls for tests, because it
242 * can take 1-10 seconds to find colliding objects. Mocking frameworks that
243 * can do magic to mock static method calls still can't do so for a system
244 * class, so we need the indirection. In production, Hotspot should still
245 * recognize that the call is 1-morphic and should still be willing to
246 * inline it if necessary.
247 */
248 int identityHashCode(Object object) {
249 return System.identityHashCode(object);
250 }
251 }
252
253 /**
254 * Returns an ordering that compares objects by the natural ordering of their
255 * string representations as returned by {@code toString()}. It does not
256 * support null values.
257 *
258 * <p>The comparator is serializable.
259 */
260 @GwtCompatible(serializable = true)
261 public static Ordering<Object> usingToString() {
262 return UsingToStringOrdering.INSTANCE;
263 }
264
265 /**
266 * Returns an ordering which tries each given comparator in order until a
267 * non-zero result is found, returning that result, and returning zero only if
268 * all comparators return zero. The returned ordering is based on the state of
269 * the {@code comparators} iterable at the time it was provided to this
270 * method.
271 *
272 * <p>The returned ordering is equivalent to that produced using {@code
273 * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}.
274 *
275 * <p><b>Warning:</b> Supplying an argument with undefined iteration order,
276 * such as a {@link HashSet}, will produce non-deterministic results.
277 *
278 * @param comparators the comparators to try in order
279 */
280 @GwtCompatible(serializable = true)
281 public static <T> Ordering<T> compound(
282 Iterable<? extends Comparator<? super T>> comparators) {
283 return new CompoundOrdering<T>(comparators);
284 }
285
286 /**
287 * Constructs a new instance of this class (only invokable by the subclass
288 * constructor, typically implicit).
289 */
290 protected Ordering() {}
291
292 // Non-static factories
293
294 /**
295 * Returns an ordering which first uses the ordering {@code this}, but which
296 * in the event of a "tie", then delegates to {@code secondaryComparator}.
297 * For example, to sort a bug list first by status and second by priority, you
298 * might use {@code byStatus.compound(byPriority)}. For a compound ordering
299 * with three or more components, simply chain multiple calls to this method.
300 *
301 * <p>An ordering produced by this method, or a chain of calls to this method,
302 * is equivalent to one created using {@link Ordering#compound(Iterable)} on
303 * the same component comparators.
304 */
305 @GwtCompatible(serializable = true)
306 public <U extends T> Ordering<U> compound(
307 Comparator<? super U> secondaryComparator) {
308 return new CompoundOrdering<U>(this, checkNotNull(secondaryComparator));
309 }
310
311 /**
312 * Returns the reverse of this ordering; the {@code Ordering} equivalent to
313 * {@link Collections#reverseOrder(Comparator)}.
314 */
315 // type parameter <S> lets us avoid the extra <String> in statements like:
316 // Ordering<String> o = Ordering.<String>natural().reverse();
317 @GwtCompatible(serializable = true)
318 public <S extends T> Ordering<S> reverse() {
319 return new ReverseOrdering<S>(this);
320 }
321
322 /**
323 * Returns a new ordering on {@code F} which orders elements by first applying
324 * a function to them, then comparing those results using {@code this}. For
325 * example, to compare objects by their string forms, in a case-insensitive
326 * manner, use: <pre> {@code
327 *
328 * Ordering.from(String.CASE_INSENSITIVE_ORDER)
329 * .onResultOf(Functions.toStringFunction())}</pre>
330 */
331 @GwtCompatible(serializable = true)
332 public <F> Ordering<F> onResultOf(Function<F, ? extends T> function) {
333 return new ByFunctionOrdering<F, T>(function, this);
334 }
335
336 /**
337 * Returns a new ordering which sorts iterables by comparing corresponding
338 * elements pairwise until a nonzero result is found; imposes "dictionary
339 * order". If the end of one iterable is reached, but not the other, the
340 * shorter iterable is considered to be less than the longer one. For example,
341 * a lexicographical natural ordering over integers considers {@code
342 * [] < [1] < [1, 1] < [1, 2] < [2]}.
343 *
344 * <p>Note that {@code ordering.lexicographical().reverse()} is not
345 * equivalent to {@code ordering.reverse().lexicographical()} (consider how
346 * each would order {@code [1]} and {@code [1, 1]}).
347 *
348 * @since 2
349 */
350 @GwtCompatible(serializable = true)
351 // type parameter <S> lets us avoid the extra <String> in statements like:
352 // Ordering<Iterable<String>> o =
353 // Ordering.<String>natural().lexicographical();
354 public <S extends T> Ordering<Iterable<S>> lexicographical() {
355 /*
356 * Note that technically the returned ordering should be capable of
357 * handling not just {@code Iterable<S>} instances, but also any {@code
358 * Iterable<? extends S>}. However, the need for this comes up so rarely
359 * that it doesn't justify making everyone else deal with the very ugly
360 * wildcard.
361 */
362 return new LexicographicalOrdering<S>(this);
363 }
364
365 /**
366 * Returns an ordering that treats {@code null} as less than all other values
367 * and uses {@code this} to compare non-null values.
368 */
369 // type parameter <S> lets us avoid the extra <String> in statements like:
370 // Ordering<String> o = Ordering.<String>natural().nullsFirst();
371 @GwtCompatible(serializable = true)
372 public <S extends T> Ordering<S> nullsFirst() {
373 return new NullsFirstOrdering<S>(this);
374 }
375
376 /**
377 * Returns an ordering that treats {@code null} as greater than all other
378 * values and uses this ordering to compare non-null values.
379 */
380 // type parameter <S> lets us avoid the extra <String> in statements like:
381 // Ordering<String> o = Ordering.<String>natural().nullsLast();
382 @GwtCompatible(serializable = true)
383 public <S extends T> Ordering<S> nullsLast() {
384 return new NullsLastOrdering<S>(this);
385 }
386
387 // Regular instance methods
388
389 // Override to add @Nullable
390 @Override public abstract int compare(@Nullable T left, @Nullable T right);
391
392 /**
393 * Returns the {@code k} least elements of the given iterable according to
394 * this ordering, in order from least to greatest. If there are fewer than
395 * {@code k} elements present, all will be included.
396 *
397 * <p>The implementation does not necessarily use a <em>stable</em> sorting
398 * algorithm; when multiple elements are equivalent, it is undefined which
399 * will come first.
400 *
401 * @return an immutable {@code RandomAccess} list of the {@code k} least
402 * elements in ascending order
403 * @throws IllegalArgumentException if {@code k} is negative
404 * @since 8
405 */
406 @Beta
407 public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) {
408 checkArgument(k >= 0, "%d is negative", k);
409
410 // values is not an E[], but we use it as such for readability. Hack.
411 @SuppressWarnings("unchecked")
412 E[] values = (E[]) Iterables.toArray(iterable);
413
414 // TODO(nshupe): also sort whole list if k is *near* values.length?
415 // TODO(kevinb): benchmark this impl against hand-coded heap
416 E[] resultArray;
417 if (values.length <= k) {
418 Arrays.sort(values, this);
419 resultArray = values;
420 } else {
421 quicksortLeastK(values, 0, values.length - 1, k);
422
423 // this is not an E[], but we use it as such for readability. Hack.
424 @SuppressWarnings("unchecked")
425 E[] tmp = (E[]) new Object[k];
426 resultArray = tmp;
427 System.arraycopy(values, 0, resultArray, 0, k);
428 }
429
430 return Collections.unmodifiableList(Arrays.asList(resultArray));
431 }
432
433 /**
434 * Returns the {@code k} greatest elements of the given iterable according to
435 * this ordering, in order from greatest to least. If there are fewer than
436 * {@code k} elements present, all will be included.
437 *
438 * <p>The implementation does not necessarily use a <em>stable</em> sorting
439 * algorithm; when multiple elements are equivalent, it is undefined which
440 * will come first.
441 *
442 * @return an immutable {@code RandomAccess} list of the {@code k} greatest
443 * elements in <i>descending order</i>
444 * @throws IllegalArgumentException if {@code k} is negative
445 * @since 8
446 */
447 @Beta
448 public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) {
449 // TODO(kevinb): see if delegation is hurting performance noticeably
450 // TODO(kevinb): if we change this implementation, add full unit tests.
451 return reverse().leastOf(iterable, k);
452 }
453
454 private <E extends T> void quicksortLeastK(
455 E[] values, int left, int right, int k) {
456 if (right > left) {
457 int pivotIndex = (left + right) >>> 1; // left + ((right - left) / 2)
458 int pivotNewIndex = partition(values, left, right, pivotIndex);
459 quicksortLeastK(values, left, pivotNewIndex - 1, k);
460 if (pivotNewIndex < k) {
461 quicksortLeastK(values, pivotNewIndex + 1, right, k);
462 }
463 }
464 }
465
466 private <E extends T> int partition(
467 E[] values, int left, int right, int pivotIndex) {
468 E pivotValue = values[pivotIndex];
469
470 values[pivotIndex] = values[right];
471 values[right] = pivotValue;
472
473 int storeIndex = left;
474 for (int i = left; i < right; i++) {
475 if (compare(values[i], pivotValue) < 0) {
476 ObjectArrays.swap(values, storeIndex, i);
477 storeIndex++;
478 }
479 }
480 ObjectArrays.swap(values, right, storeIndex);
481 return storeIndex;
482 }
483
484 /**
485 * {@link Collections#binarySearch(List, Object, Comparator) Searches}
486 * {@code sortedList} for {@code key} using the binary search algorithm. The
487 * list must be sorted using this ordering.
488 *
489 * @param sortedList the list to be searched
490 * @param key the key to be searched for
491 */
492 public int binarySearch(List<? extends T> sortedList, @Nullable T key) {
493 return Collections.binarySearch(sortedList, key, this);
494 }
495
496 /**
497 * Returns a copy of the given iterable sorted by this ordering. The input is
498 * not modified. The returned list is modifiable, serializable, and has random
499 * access.
500 *
501 * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard
502 * elements that are duplicates according to the comparator. The sort
503 * performed is <i>stable</i>, meaning that such elements will appear in the
504 * resulting list in the same order they appeared in the input.
505 *
506 * @param iterable the elements to be copied and sorted
507 * @return a new list containing the given elements in sorted order
508 */
509 public <E extends T> List<E> sortedCopy(Iterable<E> iterable) {
510 List<E> list = Lists.newArrayList(iterable);
511 Collections.sort(list, this);
512 return list;
513 }
514
515 /**
516 * Returns an <i>immutable</i> copy of the given iterable sorted by this
517 * ordering. The input is not modified.
518 *
519 * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard
520 * elements that are duplicates according to the comparator. The sort
521 * performed is <i>stable</i>, meaning that such elements will appear in the
522 * resulting list in the same order they appeared in the input.
523 *
524 * @param iterable the elements to be copied and sorted
525 * @return a new immutable list containing the given elements in sorted order
526 * @throws NullPointerException if {@code iterable} or any of its elements is
527 * null
528 * @since 3
529 */
530 public <E extends T> ImmutableList<E> immutableSortedCopy(
531 Iterable<E> iterable) {
532 return ImmutableList.copyOf(sortedCopy(iterable));
533 }
534
535 /**
536 * Returns {@code true} if each element in {@code iterable} after the first is
537 * greater than or equal to the element that preceded it, according to this
538 * ordering. Note that this is always true when the iterable has fewer than
539 * two elements.
540 */
541 public boolean isOrdered(Iterable<? extends T> iterable) {
542 Iterator<? extends T> it = iterable.iterator();
543 if (it.hasNext()) {
544 T prev = it.next();
545 while (it.hasNext()) {
546 T next = it.next();
547 if (compare(prev, next) > 0) {
548 return false;
549 }
550 prev = next;
551 }
552 }
553 return true;
554 }
555
556 /**
557 * Returns {@code true} if each element in {@code iterable} after the first is
558 * <i>strictly</i> greater than the element that preceded it, according to
559 * this ordering. Note that this is always true when the iterable has fewer
560 * than two elements.
561 */
562 public boolean isStrictlyOrdered(Iterable<? extends T> iterable) {
563 Iterator<? extends T> it = iterable.iterator();
564 if (it.hasNext()) {
565 T prev = it.next();
566 while (it.hasNext()) {
567 T next = it.next();
568 if (compare(prev, next) >= 0) {
569 return false;
570 }
571 prev = next;
572 }
573 }
574 return true;
575 }
576
577 /**
578 * Returns the greatest of the specified values according to this ordering. If
579 * there are multiple greatest values, the first of those is returned.
580 *
581 * @param iterable the iterable whose maximum element is to be determined
582 * @throws NoSuchElementException if {@code iterable} is empty
583 * @throws ClassCastException if the parameters are not <i>mutually
584 * comparable</i> under this ordering.
585 */
586 public <E extends T> E max(Iterable<E> iterable) {
587 Iterator<E> iterator = iterable.iterator();
588
589 // let this throw NoSuchElementException as necessary
590 E maxSoFar = iterator.next();
591
592 while (iterator.hasNext()) {
593 maxSoFar = max(maxSoFar, iterator.next());
594 }
595
596 return maxSoFar;
597 }
598
599 /**
600 * Returns the greatest of the specified values according to this ordering. If
601 * there are multiple greatest values, the first of those is returned.
602 *
603 * @param a value to compare, returned if greater than or equal to the rest.
604 * @param b value to compare
605 * @param c value to compare
606 * @param rest values to compare
607 * @throws ClassCastException if the parameters are not <i>mutually
608 * comparable</i> under this ordering.
609 */
610 public <E extends T> E max(
611 @Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
612 E maxSoFar = max(max(a, b), c);
613
614 for (E r : rest) {
615 maxSoFar = max(maxSoFar, r);
616 }
617
618 return maxSoFar;
619 }
620
621 /**
622 * Returns the greater of the two values according to this ordering. If the
623 * values compare as 0, the first is returned.
624 *
625 * <p><b>Implementation note:</b> this method is invoked by the default
626 * implementations of the other {@code max} overloads, so overriding it will
627 * affect their behavior.
628 *
629 * @param a value to compare, returned if greater than or equal to b.
630 * @param b value to compare.
631 * @throws ClassCastException if the parameters are not <i>mutually
632 * comparable</i> under this ordering.
633 */
634 public <E extends T> E max(@Nullable E a, @Nullable E b) {
635 return compare(a, b) >= 0 ? a : b;
636 }
637
638 /**
639 * Returns the least of the specified values according to this ordering. If
640 * there are multiple least values, the first of those is returned.
641 *
642 * @param iterable the iterable whose minimum element is to be determined
643 * @throws NoSuchElementException if {@code iterable} is empty
644 * @throws ClassCastException if the parameters are not <i>mutually
645 * comparable</i> under this ordering.
646 */
647 public <E extends T> E min(Iterable<E> iterable) {
648 Iterator<E> iterator = iterable.iterator();
649
650 // let this throw NoSuchElementException as necessary
651 E minSoFar = iterator.next();
652
653 while (iterator.hasNext()) {
654 minSoFar = min(minSoFar, iterator.next());
655 }
656
657 return minSoFar;
658 }
659
660 /**
661 * Returns the least of the specified values according to this ordering. If
662 * there are multiple least values, the first of those is returned.
663 *
664 * @param a value to compare, returned if less than or equal to the rest.
665 * @param b value to compare
666 * @param c value to compare
667 * @param rest values to compare
668 * @throws ClassCastException if the parameters are not <i>mutually
669 * comparable</i> under this ordering.
670 */
671 public <E extends T> E min(
672 @Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
673 E minSoFar = min(min(a, b), c);
674
675 for (E r : rest) {
676 minSoFar = min(minSoFar, r);
677 }
678
679 return minSoFar;
680 }
681
682 /**
683 * Returns the lesser of the two values according to this ordering. If the
684 * values compare as 0, the first is returned.
685 *
686 * <p><b>Implementation note:</b> this method is invoked by the default
687 * implementations of the other {@code min} overloads, so overriding it will
688 * affect their behavior.
689 *
690 * @param a value to compare, returned if less than or equal to b.
691 * @param b value to compare.
692 * @throws ClassCastException if the parameters are not <i>mutually
693 * comparable</i> under this ordering.
694 */
695 public <E extends T> E min(@Nullable E a, @Nullable E b) {
696 return compare(a, b) <= 0 ? a : b;
697 }
698
699 // Never make these public
700 static final int LEFT_IS_GREATER = 1;
701 static final int RIGHT_IS_GREATER = -1;
702 }