< prev index next >

src/java.base/share/classes/java/util/Comparator.java

Print this page




  25 
  26 package java.util;
  27 
  28 import java.io.Serializable;
  29 import java.util.function.Function;
  30 import java.util.function.ToIntFunction;
  31 import java.util.function.ToLongFunction;
  32 import java.util.function.ToDoubleFunction;
  33 import java.util.Comparators;
  34 
  35 /**
  36  * A comparison function, which imposes a <i>total ordering</i> on some
  37  * collection of objects.  Comparators can be passed to a sort method (such
  38  * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link
  39  * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control
  40  * over the sort order.  Comparators can also be used to control the order of
  41  * certain data structures (such as {@link SortedSet sorted sets} or {@link
  42  * SortedMap sorted maps}), or to provide an ordering for collections of
  43  * objects that don't have a {@link Comparable natural ordering}.<p>
  44  *
  45  * The ordering imposed by a comparator <tt>c</tt> on a set of elements
  46  * <tt>S</tt> is said to be <i>consistent with equals</i> if and only if
  47  * <tt>c.compare(e1, e2)==0</tt> has the same boolean value as
  48  * <tt>e1.equals(e2)</tt> for every <tt>e1</tt> and <tt>e2</tt> in
  49  * <tt>S</tt>.<p>
  50  *
  51  * Caution should be exercised when using a comparator capable of imposing an
  52  * ordering inconsistent with equals to order a sorted set (or sorted map).
  53  * Suppose a sorted set (or sorted map) with an explicit comparator <tt>c</tt>
  54  * is used with elements (or keys) drawn from a set <tt>S</tt>.  If the
  55  * ordering imposed by <tt>c</tt> on <tt>S</tt> is inconsistent with equals,
  56  * the sorted set (or sorted map) will behave "strangely."  In particular the
  57  * sorted set (or sorted map) will violate the general contract for set (or
  58  * map), which is defined in terms of <tt>equals</tt>.<p>
  59  *
  60  * For example, suppose one adds two elements {@code a} and {@code b} such that
  61  * {@code (a.equals(b) && c.compare(a, b) != 0)}
  62  * to an empty {@code TreeSet} with comparator {@code c}.
  63  * The second {@code add} operation will return
  64  * true (and the size of the tree set will increase) because {@code a} and
  65  * {@code b} are not equivalent from the tree set's perspective, even though
  66  * this is contrary to the specification of the
  67  * {@link Set#add Set.add} method.<p>
  68  *
  69  * Note: It is generally a good idea for comparators to also implement
  70  * <tt>java.io.Serializable</tt>, as they may be used as ordering methods in
  71  * serializable data structures (like {@link TreeSet}, {@link TreeMap}).  In
  72  * order for the data structure to serialize successfully, the comparator (if
  73  * provided) must implement <tt>Serializable</tt>.<p>
  74  *
  75  * For the mathematically inclined, the <i>relation</i> that defines the
  76  * <i>imposed ordering</i> that a given comparator <tt>c</tt> imposes on a
  77  * given set of objects <tt>S</tt> is:<pre>
  78  *       {(x, y) such that c.compare(x, y) &lt;= 0}.
  79  * </pre> The <i>quotient</i> for this total order is:<pre>
  80  *       {(x, y) such that c.compare(x, y) == 0}.
  81  * </pre>
  82  *
  83  * It follows immediately from the contract for <tt>compare</tt> that the
  84  * quotient is an <i>equivalence relation</i> on <tt>S</tt>, and that the
  85  * imposed ordering is a <i>total order</i> on <tt>S</tt>.  When we say that
  86  * the ordering imposed by <tt>c</tt> on <tt>S</tt> is <i>consistent with
  87  * equals</i>, we mean that the quotient for the ordering is the equivalence
  88  * relation defined by the objects' {@link Object#equals(Object)
  89  * equals(Object)} method(s):<pre>
  90  *     {(x, y) such that x.equals(y)}. </pre>
  91  *
  92  * <p>Unlike {@code Comparable}, a comparator may optionally permit
  93  * comparison of null arguments, while maintaining the requirements for
  94  * an equivalence relation.
  95  *
  96  * <p>This interface is a member of the
  97  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  98  * Java Collections Framework</a>.
  99  *
 100  * @param <T> the type of objects that may be compared by this comparator
 101  *
 102  * @author  Josh Bloch
 103  * @author  Neal Gafter
 104  * @see Comparable
 105  * @see java.io.Serializable
 106  * @since 1.2
 107  */
 108 @FunctionalInterface
 109 public interface Comparator<T> {
 110     /**
 111      * Compares its two arguments for order.  Returns a negative integer,
 112      * zero, or a positive integer as the first argument is less than, equal
 113      * to, or greater than the second.<p>
 114      *
 115      * In the foregoing description, the notation
 116      * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
 117      * <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
 118      * <tt>0</tt>, or <tt>1</tt> according to whether the value of
 119      * <i>expression</i> is negative, zero or positive.<p>
 120      *
 121      * The implementor must ensure that <tt>sgn(compare(x, y)) ==
 122      * -sgn(compare(y, x))</tt> for all <tt>x</tt> and <tt>y</tt>.  (This
 123      * implies that <tt>compare(x, y)</tt> must throw an exception if and only
 124      * if <tt>compare(y, x)</tt> throws an exception.)<p>
 125      *
 126      * The implementor must also ensure that the relation is transitive:
 127      * <tt>((compare(x, y)&gt;0) &amp;&amp; (compare(y, z)&gt;0))</tt> implies
 128      * <tt>compare(x, z)&gt;0</tt>.<p>
 129      *
 130      * Finally, the implementor must ensure that <tt>compare(x, y)==0</tt>
 131      * implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all
 132      * <tt>z</tt>.<p>
 133      *
 134      * It is generally the case, but <i>not</i> strictly required that
 135      * <tt>(compare(x, y)==0) == (x.equals(y))</tt>.  Generally speaking,
 136      * any comparator that violates this condition should clearly indicate
 137      * this fact.  The recommended language is "Note: this comparator
 138      * imposes orderings that are inconsistent with equals."
 139      *
 140      * @param o1 the first object to be compared.
 141      * @param o2 the second object to be compared.
 142      * @return a negative integer, zero, or a positive integer as the
 143      *         first argument is less than, equal to, or greater than the
 144      *         second.
 145      * @throws NullPointerException if an argument is null and this
 146      *         comparator does not permit null arguments
 147      * @throws ClassCastException if the arguments' types prevent them from
 148      *         being compared by this comparator.
 149      */
 150     int compare(T o1, T o2);
 151 
 152     /**
 153      * Indicates whether some other object is &quot;equal to&quot; this
 154      * comparator.  This method must obey the general contract of
 155      * {@link Object#equals(Object)}.  Additionally, this method can return
 156      * <tt>true</tt> <i>only</i> if the specified object is also a comparator
 157      * and it imposes the same ordering as this comparator.  Thus,
 158      * <code>comp1.equals(comp2)</code> implies that <tt>sgn(comp1.compare(o1,
 159      * o2))==sgn(comp2.compare(o1, o2))</tt> for every object reference
 160      * <tt>o1</tt> and <tt>o2</tt>.<p>
 161      *
 162      * Note that it is <i>always</i> safe <i>not</i> to override
 163      * <tt>Object.equals(Object)</tt>.  However, overriding this method may,
 164      * in some cases, improve performance by allowing programs to determine
 165      * that two distinct comparators impose the same order.
 166      *
 167      * @param   obj   the reference object with which to compare.
 168      * @return  <code>true</code> only if the specified object is also
 169      *          a comparator and it imposes the same ordering as this
 170      *          comparator.
 171      * @see Object#equals(Object)
 172      * @see Object#hashCode()
 173      */
 174     boolean equals(Object obj);
 175 
 176     /**
 177      * Returns a comparator that imposes the reverse ordering of this
 178      * comparator.
 179      *
 180      * @return a comparator that imposes the reverse ordering of this
 181      *         comparator.
 182      * @since 1.8
 183      */
 184     default Comparator<T> reversed() {
 185         return Collections.reverseOrder(this);
 186     }
 187 
 188     /**




  25 
  26 package java.util;
  27 
  28 import java.io.Serializable;
  29 import java.util.function.Function;
  30 import java.util.function.ToIntFunction;
  31 import java.util.function.ToLongFunction;
  32 import java.util.function.ToDoubleFunction;
  33 import java.util.Comparators;
  34 
  35 /**
  36  * A comparison function, which imposes a <i>total ordering</i> on some
  37  * collection of objects.  Comparators can be passed to a sort method (such
  38  * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link
  39  * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control
  40  * over the sort order.  Comparators can also be used to control the order of
  41  * certain data structures (such as {@link SortedSet sorted sets} or {@link
  42  * SortedMap sorted maps}), or to provide an ordering for collections of
  43  * objects that don't have a {@link Comparable natural ordering}.<p>
  44  *
  45  * The ordering imposed by a comparator {@code c} on a set of elements
  46  * {@code S} is said to be <i>consistent with equals</i> if and only if
  47  * {@code c.compare(e1, e2)==0} has the same boolean value as
  48  * {@code e1.equals(e2)} for every {@code e1} and {@code e2} in
  49  * {@code S}.<p>
  50  *
  51  * Caution should be exercised when using a comparator capable of imposing an
  52  * ordering inconsistent with equals to order a sorted set (or sorted map).
  53  * Suppose a sorted set (or sorted map) with an explicit comparator {@code c}
  54  * is used with elements (or keys) drawn from a set {@code S}.  If the
  55  * ordering imposed by {@code c} on {@code S} is inconsistent with equals,
  56  * the sorted set (or sorted map) will behave "strangely."  In particular the
  57  * sorted set (or sorted map) will violate the general contract for set (or
  58  * map), which is defined in terms of {@code equals}.<p>
  59  *
  60  * For example, suppose one adds two elements {@code a} and {@code b} such that
  61  * {@code (a.equals(b) && c.compare(a, b) != 0)}
  62  * to an empty {@code TreeSet} with comparator {@code c}.
  63  * The second {@code add} operation will return
  64  * true (and the size of the tree set will increase) because {@code a} and
  65  * {@code b} are not equivalent from the tree set's perspective, even though
  66  * this is contrary to the specification of the
  67  * {@link Set#add Set.add} method.<p>
  68  *
  69  * Note: It is generally a good idea for comparators to also implement
  70  * {@code java.io.Serializable}, as they may be used as ordering methods in
  71  * serializable data structures (like {@link TreeSet}, {@link TreeMap}).  In
  72  * order for the data structure to serialize successfully, the comparator (if
  73  * provided) must implement {@code Serializable}.<p>
  74  *
  75  * For the mathematically inclined, the <i>relation</i> that defines the
  76  * <i>imposed ordering</i> that a given comparator {@code c} imposes on a
  77  * given set of objects {@code S} is:<pre>
  78  *       {(x, y) such that c.compare(x, y) &lt;= 0}.
  79  * </pre> The <i>quotient</i> for this total order is:<pre>
  80  *       {(x, y) such that c.compare(x, y) == 0}.
  81  * </pre>
  82  *
  83  * It follows immediately from the contract for {@code compare} that the
  84  * quotient is an <i>equivalence relation</i> on {@code S}, and that the
  85  * imposed ordering is a <i>total order</i> on {@code S}.  When we say that
  86  * the ordering imposed by {@code c} on {@code S} is <i>consistent with
  87  * equals</i>, we mean that the quotient for the ordering is the equivalence
  88  * relation defined by the objects' {@link Object#equals(Object)
  89  * equals(Object)} method(s):<pre>
  90  *     {(x, y) such that x.equals(y)}. </pre>
  91  *
  92  * <p>Unlike {@code Comparable}, a comparator may optionally permit
  93  * comparison of null arguments, while maintaining the requirements for
  94  * an equivalence relation.
  95  *
  96  * <p>This interface is a member of the
  97  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  98  * Java Collections Framework</a>.
  99  *
 100  * @param <T> the type of objects that may be compared by this comparator
 101  *
 102  * @author  Josh Bloch
 103  * @author  Neal Gafter
 104  * @see Comparable
 105  * @see java.io.Serializable
 106  * @since 1.2
 107  */
 108 @FunctionalInterface
 109 public interface Comparator<T> {
 110     /**
 111      * Compares its two arguments for order.  Returns a negative integer,
 112      * zero, or a positive integer as the first argument is less than, equal
 113      * to, or greater than the second.<p>
 114      *
 115      * In the foregoing description, the notation
 116      * {@code sgn(}<i>expression</i>{@code )} designates the mathematical
 117      * <i>signum</i> function, which is defined to return one of {@code -1},
 118      * {@code 0}, or {@code 1} according to whether the value of
 119      * <i>expression</i> is negative, zero or positive.<p>
 120      *
 121      * The implementor must ensure that {@code sgn(compare(x, y)) ==
 122      * -sgn(compare(y, x))} for all {@code x} and {@code y}.  (This
 123      * implies that {@code compare(x, y)} must throw an exception if and only
 124      * if {@code compare(y, x)} throws an exception.)<p>
 125      *
 126      * The implementor must also ensure that the relation is transitive:
 127      * {@code ((compare(x, y)>0) && (compare(y, z)>0))} implies
 128      * {@code compare(x, z)>0}.<p>
 129      *
 130      * Finally, the implementor must ensure that {@code compare(x, y)==0}
 131      * implies that {@code sgn(compare(x, z))==sgn(compare(y, z))} for all
 132      * {@code z}.<p>
 133      *
 134      * It is generally the case, but <i>not</i> strictly required that
 135      * {@code (compare(x, y)==0) == (x.equals(y))}.  Generally speaking,
 136      * any comparator that violates this condition should clearly indicate
 137      * this fact.  The recommended language is "Note: this comparator
 138      * imposes orderings that are inconsistent with equals."
 139      *
 140      * @param o1 the first object to be compared.
 141      * @param o2 the second object to be compared.
 142      * @return a negative integer, zero, or a positive integer as the
 143      *         first argument is less than, equal to, or greater than the
 144      *         second.
 145      * @throws NullPointerException if an argument is null and this
 146      *         comparator does not permit null arguments
 147      * @throws ClassCastException if the arguments' types prevent them from
 148      *         being compared by this comparator.
 149      */
 150     int compare(T o1, T o2);
 151 
 152     /**
 153      * Indicates whether some other object is &quot;equal to&quot; this
 154      * comparator.  This method must obey the general contract of
 155      * {@link Object#equals(Object)}.  Additionally, this method can return
 156      * {@code true} <i>only</i> if the specified object is also a comparator
 157      * and it imposes the same ordering as this comparator.  Thus,
 158      * {@code comp1.equals(comp2)} implies that {@code sgn(comp1.compare(o1,
 159      * o2))==sgn(comp2.compare(o1, o2))} for every object reference
 160      * {@code o1} and {@code o2}.<p>
 161      *
 162      * Note that it is <i>always</i> safe <i>not</i> to override
 163      * {@code Object.equals(Object)}.  However, overriding this method may,
 164      * in some cases, improve performance by allowing programs to determine
 165      * that two distinct comparators impose the same order.
 166      *
 167      * @param   obj   the reference object with which to compare.
 168      * @return  {@code true} only if the specified object is also
 169      *          a comparator and it imposes the same ordering as this
 170      *          comparator.
 171      * @see Object#equals(Object)
 172      * @see Object#hashCode()
 173      */
 174     boolean equals(Object obj);
 175 
 176     /**
 177      * Returns a comparator that imposes the reverse ordering of this
 178      * comparator.
 179      *
 180      * @return a comparator that imposes the reverse ordering of this
 181      *         comparator.
 182      * @since 1.8
 183      */
 184     default Comparator<T> reversed() {
 185         return Collections.reverseOrder(this);
 186     }
 187 
 188     /**


< prev index next >