Class Ordinal
java.lang.Object
com.google.mu.util.Ordinal
- All Implemented Interfaces:
Comparable<Ordinal>
This class provides type-safe transition between 1-based Ordinal and 0-based indexes that are
commonly used to index arrays and lists. This is useful especially to translate between
end-user friendly numbers and machine-friendly index numbers, like for example, to report error
messages.
Users should immediately wrap 1-based numbers as Ordinal
instances to take advantage
of the static type safety, to avoid 1-off errors and to use the extra utilities in this class.
Small ordinal numbers are pre-cached to avoid incurring allocation cost.
- Since:
- 4.6
-
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionint
Compares tothat
according to natural order.boolean
static Ordinal
first()
Returns the first ordinal.static Ordinal
fromIndex
(int zeroBased) Returns instance corresponding to thezeroBased
index.int
hashCode()
int
Returns the distance betweenthis
andthat
.natural()
Returns the infinite stream of natural ordinals starting from "1st".next()
Returns the next ordinal.static Ordinal
of
(int oneBased) Returns instance corresponding to theoneBased
number.static Ordinal
Returns instance corresponding to the ordinal of the Enum objecte
.previous()
Returns the previous ordinal.static Ordinal
second()
Returns the second ordinal.int
toIndex()
Returns the 0-based index, such that"1st"
will map to 0, thus can be used to read and write elements in arrays and lists.toString()
Returns the string representation of this ordinal.
-
Field Details
-
MAX_VALUE
-
-
Method Details
-
first
Returns the first ordinal. -
second
-
natural
-
of
Returns instance corresponding to theoneBased
number. Small integer numbers in the range of[1, 100]
are cached.- Throws:
IllegalArgumentException
- ifnum
is not positive.
-
of
-
fromIndex
Returns instance corresponding to thezeroBased
index. That is: index0
corresponds to"1st"
and index1
for"2nd"
etc.- Throws:
IllegalArgumentException
- ifnum
is negative.
-
toIndex
public int toIndex()Returns the 0-based index, such that"1st"
will map to 0, thus can be used to read and write elements in arrays and lists. -
next
-
previous
-
minus
Returns the distance betweenthis
andthat
.Some examples:
1st.minus(2nd) => -1 5th.minus(2nd) => 3
- Since:
- 7.0
-
compareTo
Compares tothat
according to natural order.- Specified by:
compareTo
in interfaceComparable<Ordinal>
-
hashCode
-
equals
-
toString
-