The general contract for values whose magnitude can be
compared. Comparable
imposes a total ordering upon
instances of any type that satisfies the interface.
If a type T
satisfies Comparable<T>
, then instances
of T
may be compared using the comparison operators
<
, >
, <=
, >=
.
assert (x>=0.0);
A ternary comparison is useful for asserting lower and upper bounds.
assert (0.0<=x<1.0);
Finally, the compare operator <=>
may be used to
produce an instance of Comparison
.
switch (x<=>y) case (equal) { print("same same"); } case (smaller) { print("x smaller"); } case (larger) { print("y smaller"); }
The total order of a type must be consistent with the definition of equality for the type. That is, there are three mutually exclusive possibilities:
x<y
,x>y
, orx==y
(These possibilities are expressed by the enumerated
instances smaller
, larger
, and equal
of
Comparison
.)
The order imposed by Comparable
is sometimes called the
natural order of a type, to reflect the fact that any
function of type Comparison(T,T)
might determine a
different order. Thus, some order-related operations come
in two flavors: a flavor that depends upon the natural
order, and a flavor which accepts an arbitrary comparator
function. Examples are:
sort()
vs Iterable.sort()
andmax()
vs Iterable.max()
.Comparison
, sort()
, max()
, min()
, largest()
, smallest()
no type hierarchy
no supertypes hierarchy
Methods | |
compare | Source Codeshared formal Comparison compare(Other other) Compares this value with the given value, returning:
For any two values x <=> y Implementations must respect the constraints that:
See also Object.equals() |
largerThan | Source Codeshared default Boolean largerThan(Other other) Determines if this value is strictly larger than the given value. Since 1.1.0 |
notLargerThan | Source Codeshared default Boolean notLargerThan(Other other) Determines if this value is smaller than or equal to the given value. Since 1.1.0 |
notSmallerThan | Source Codeshared default Boolean notSmallerThan(Other other) Determines if this value is larger than or equal to the given value. Since 1.1.0 |
smallerThan | Source Codeshared default Boolean smallerThan(Other other) Determines if this value is strictly smaller than the given value. Since 1.1.0 |
Inherited Methods |
Methods inherited from: Object |