Class Range<C extends java.lang.Comparable>
- java.lang.Object
-
- com.google.common.collect.Range<C>
-
- All Implemented Interfaces:
Predicate<C>,java.io.Serializable,java.util.function.Predicate<C>
@GwtCompatible @Immutable(containerOf="C") public final class Range<C extends java.lang.Comparable> extends java.lang.Object implements Predicate<C>, java.io.Serializable
A range (or "interval") defines the boundaries around a contiguous span of values of someComparabletype; for example, "integers from 1 to 100 inclusive." Note that it is not possible to iterate over these contained values. To do so, pass this range instance and an appropriateDiscreteDomaintoContiguousSet.create(com.google.common.collect.Range<C>, com.google.common.collect.DiscreteDomain<C>).Types of ranges
Each end of the range may be bounded or unbounded. If bounded, there is an associated endpoint value, and the range is considered to be either open (does not include the endpoint) or closed (includes the endpoint) on that side. With three possibilities on each side, this yields nine basic types of ranges, enumerated below. (Notation: a square bracket (
[ ]) indicates that the range is closed on that side; a parenthesis (( )) means it is either open or unbounded. The construct{x | statement}is read "the set of all x such that statement.")Range Types Notation Definition Factory method (a..b){x | a < x < b}open[a..b]{x | a <= x <= b}closed(a..b]{x | a < x <= b}openClosed[a..b){x | a <= x < b}closedOpen(a..+∞){x | x > a}greaterThan[a..+∞){x | x >= a}atLeast(-∞..b){x | x < b}lessThan(-∞..b]{x | x <= b}atMost(-∞..+∞){x}allWhen both endpoints exist, the upper endpoint may not be less than the lower. The endpoints may be equal only if at least one of the bounds is closed:
[a..a]: a singleton range[a..a); (a..a]: empty ranges; also valid(a..a): invalid; an exception will be thrown
Warnings
- Use immutable value types only, if at all possible. If you must use a mutable type, do not allow the endpoint instances to mutate after the range is created!
- Your value type's comparison method should be consistent with
equals if at all possible. Otherwise, be aware that concepts used throughout this
documentation such as "equal", "same", "unique" and so on actually refer to whether
compareToreturns zero, not whetherequalsreturnstrue. - A class which implements
Comparable<UnrelatedType>is very broken, and will cause undefined horrible things to happen inRange. For now, the Range API does not prevent its use, because this would also rule out all ungenerified (pre-JDK1.5) data types. This may change in the future.
Other notes
- All ranges are shallow-immutable.
- Instances of this type are obtained using the static factory methods in this class.
- Ranges are convex: whenever two values are contained, all values in between them
must also be contained. More formally, for any
c1 <= c2 <= c3of typeC,r.contains(c1) && r.contains(c3)impliesr.contains(c2)). This means that aRange<Integer>can never be used to represent, say, "all prime numbers from 1 to 100." - When evaluated as a
Predicate, a range yields the same result as invokingcontains(C). - Terminology note: a range
ais said to be the maximal range having property P if, for all rangesbalso having property P,a.encloses(b). Likewise,ais minimal whenb.encloses(a)for allbhaving property P. See, for example, the definition ofintersection. - A
Rangeis serializable if it has no bounds, or if each bound is serializable.
Further reading
See the Guava User Guide article on
Range.- Since:
- 10.0
- Author:
- Kevin Bourrillion, Gregory Kick
- See Also:
- Serialized Form
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static <C extends java.lang.Comparable<?>>
Range<C>all()Returns a range that contains every value of typeC.booleanapply(C input)Deprecated.Provided only to satisfy thePredicateinterface; usecontains(C)instead.static <C extends java.lang.Comparable<?>>
Range<C>atLeast(C endpoint)Returns a range that contains all values greater than or equal toendpoint.static <C extends java.lang.Comparable<?>>
Range<C>atMost(C endpoint)Returns a range that contains all values less than or equal toendpoint.Range<C>canonical(DiscreteDomain<C> domain)Returns the canonical form of this range in the given domain.static <C extends java.lang.Comparable<?>>
Range<C>closed(C lower, C upper)Returns a range that contains all values greater than or equal tolowerand less than or equal toupper.static <C extends java.lang.Comparable<?>>
Range<C>closedOpen(C lower, C upper)Returns a range that contains all values greater than or equal tolowerand strictly less thanupper.booleancontains(C value)Returnstrueifvalueis within the bounds of this range.booleancontainsAll(java.lang.Iterable<? extends C> values)static <C extends java.lang.Comparable<?>>
Range<C>downTo(C endpoint, BoundType boundType)Returns a range from the given endpoint, which may be either inclusive (closed) or exclusive (open), with no upper bound.static <C extends java.lang.Comparable<?>>
Range<C>encloseAll(java.lang.Iterable<C> values)Returns the minimal range that contains all of the given values.booleanencloses(Range<C> other)Returnstrueif the bounds ofotherdo not extend outside the bounds of this range.booleanequals(java.lang.Object object)Returnstrueifobjectis a range having the same endpoints and bound types as this range.Range<C>gap(Range<C> otherRange)Returns the maximal range lying between this range andotherRange, if such a range exists.static <C extends java.lang.Comparable<?>>
Range<C>greaterThan(C endpoint)Returns a range that contains all values strictly greater thanendpoint.inthashCode()Returns a hash code for this range.booleanhasLowerBound()Returnstrueif this range has a lower endpoint.booleanhasUpperBound()Returnstrueif this range has an upper endpoint.Range<C>intersection(Range<C> connectedRange)Returns the maximal range enclosed by both this range andconnectedRange, if such a range exists.booleanisConnected(Range<C> other)Returnstrueif there exists a (possibly empty) range which is enclosed by both this range andother.booleanisEmpty()Returnstrueif this range is of the form[v..v)or(v..v].static <C extends java.lang.Comparable<?>>
Range<C>lessThan(C endpoint)Returns a range that contains all values strictly less thanendpoint.BoundTypelowerBoundType()Returns the type of this range's lower bound:BoundType.CLOSEDif the range includes its lower endpoint,BoundType.OPENif it does not.ClowerEndpoint()Returns the lower endpoint of this range.static <C extends java.lang.Comparable<?>>
Range<C>open(C lower, C upper)Returns a range that contains all values strictly greater thanlowerand strictly less thanupper.static <C extends java.lang.Comparable<?>>
Range<C>openClosed(C lower, C upper)Returns a range that contains all values strictly greater thanlowerand less than or equal toupper.static <C extends java.lang.Comparable<?>>
Range<C>range(C lower, BoundType lowerType, C upper, BoundType upperType)Returns a range that contains any value fromlowertoupper, where each endpoint may be either inclusive (closed) or exclusive (open).static <C extends java.lang.Comparable<?>>
Range<C>singleton(C value)Returns a range that contains only the given value.Range<C>span(Range<C> other)Returns the minimal range that encloses both this range andother.java.lang.StringtoString()Returns a string representation of this range, such as"[3..5)"(other examples are listed in the class documentation).BoundTypeupperBoundType()Returns the type of this range's upper bound:BoundType.CLOSEDif the range includes its upper endpoint,BoundType.OPENif it does not.CupperEndpoint()Returns the upper endpoint of this range.static <C extends java.lang.Comparable<?>>
Range<C>upTo(C endpoint, BoundType boundType)Returns a range with no lower bound up to the given endpoint, which may be either inclusive (closed) or exclusive (open).
-
-
-
Method Detail
-
open
public static <C extends java.lang.Comparable<?>> Range<C> open(C lower, C upper)
Returns a range that contains all values strictly greater thanlowerand strictly less thanupper.- Throws:
java.lang.IllegalArgumentException- ifloweris greater than or equal toupperjava.lang.ClassCastException- iflowerandupperare not mutually comparable- Since:
- 14.0
-
closed
public static <C extends java.lang.Comparable<?>> Range<C> closed(C lower, C upper)
Returns a range that contains all values greater than or equal tolowerand less than or equal toupper.- Throws:
java.lang.IllegalArgumentException- ifloweris greater thanupperjava.lang.ClassCastException- iflowerandupperare not mutually comparable- Since:
- 14.0
-
closedOpen
public static <C extends java.lang.Comparable<?>> Range<C> closedOpen(C lower, C upper)
Returns a range that contains all values greater than or equal tolowerand strictly less thanupper.- Throws:
java.lang.IllegalArgumentException- ifloweris greater thanupperjava.lang.ClassCastException- iflowerandupperare not mutually comparable- Since:
- 14.0
-
openClosed
public static <C extends java.lang.Comparable<?>> Range<C> openClosed(C lower, C upper)
Returns a range that contains all values strictly greater thanlowerand less than or equal toupper.- Throws:
java.lang.IllegalArgumentException- ifloweris greater thanupperjava.lang.ClassCastException- iflowerandupperare not mutually comparable- Since:
- 14.0
-
range
public static <C extends java.lang.Comparable<?>> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType)
Returns a range that contains any value fromlowertoupper, where each endpoint may be either inclusive (closed) or exclusive (open).- Throws:
java.lang.IllegalArgumentException- ifloweris greater thanupperjava.lang.ClassCastException- iflowerandupperare not mutually comparable- Since:
- 14.0
-
lessThan
public static <C extends java.lang.Comparable<?>> Range<C> lessThan(C endpoint)
Returns a range that contains all values strictly less thanendpoint.- Since:
- 14.0
-
atMost
public static <C extends java.lang.Comparable<?>> Range<C> atMost(C endpoint)
Returns a range that contains all values less than or equal toendpoint.- Since:
- 14.0
-
upTo
public static <C extends java.lang.Comparable<?>> Range<C> upTo(C endpoint, BoundType boundType)
Returns a range with no lower bound up to the given endpoint, which may be either inclusive (closed) or exclusive (open).- Since:
- 14.0
-
greaterThan
public static <C extends java.lang.Comparable<?>> Range<C> greaterThan(C endpoint)
Returns a range that contains all values strictly greater thanendpoint.- Since:
- 14.0
-
atLeast
public static <C extends java.lang.Comparable<?>> Range<C> atLeast(C endpoint)
Returns a range that contains all values greater than or equal toendpoint.- Since:
- 14.0
-
downTo
public static <C extends java.lang.Comparable<?>> Range<C> downTo(C endpoint, BoundType boundType)
Returns a range from the given endpoint, which may be either inclusive (closed) or exclusive (open), with no upper bound.- Since:
- 14.0
-
all
public static <C extends java.lang.Comparable<?>> Range<C> all()
Returns a range that contains every value of typeC.- Since:
- 14.0
-
singleton
public static <C extends java.lang.Comparable<?>> Range<C> singleton(C value)
- Since:
- 14.0
-
encloseAll
public static <C extends java.lang.Comparable<?>> Range<C> encloseAll(java.lang.Iterable<C> values)
Returns the minimal range that contains all of the given values. The returned range is closed on both ends.- Throws:
java.lang.ClassCastException- if the values are not mutually comparablejava.util.NoSuchElementException- ifvaluesis emptyjava.lang.NullPointerException- if any ofvaluesis null- Since:
- 14.0
-
hasLowerBound
public boolean hasLowerBound()
Returnstrueif this range has a lower endpoint.
-
lowerEndpoint
public C lowerEndpoint()
Returns the lower endpoint of this range.- Throws:
java.lang.IllegalStateException- if this range is unbounded below (that is,hasLowerBound()returnsfalse)
-
lowerBoundType
public BoundType lowerBoundType()
Returns the type of this range's lower bound:BoundType.CLOSEDif the range includes its lower endpoint,BoundType.OPENif it does not.- Throws:
java.lang.IllegalStateException- if this range is unbounded below (that is,hasLowerBound()returnsfalse)
-
hasUpperBound
public boolean hasUpperBound()
Returnstrueif this range has an upper endpoint.
-
upperEndpoint
public C upperEndpoint()
Returns the upper endpoint of this range.- Throws:
java.lang.IllegalStateException- if this range is unbounded above (that is,hasUpperBound()returnsfalse)
-
upperBoundType
public BoundType upperBoundType()
Returns the type of this range's upper bound:BoundType.CLOSEDif the range includes its upper endpoint,BoundType.OPENif it does not.- Throws:
java.lang.IllegalStateException- if this range is unbounded above (that is,hasUpperBound()returnsfalse)
-
isEmpty
public boolean isEmpty()
Returnstrueif this range is of the form[v..v)or(v..v]. (This does not encompass ranges of the form(v..v), because such ranges are invalid and can't be constructed at all.)Note that certain discrete ranges such as the integer range
(3..4)are not considered empty, even though they contain no actual values. In these cases, it may be helpful to preprocess ranges withcanonical(DiscreteDomain).
-
contains
public boolean contains(C value)
Returnstrueifvalueis within the bounds of this range. For example, on the range[0..2),contains(1)returnstrue, whilecontains(2)returnsfalse.
-
apply
@Deprecated public boolean apply(C input)
Deprecated.Provided only to satisfy thePredicateinterface; usecontains(C)instead.Description copied from interface:PredicateReturns the result of applying this predicate toinput(Java 8 users, see notes in the class documentation above). This method is generally expected, but not absolutely required, to have the following properties:- Its execution does not cause any observable side effects.
- The computation is consistent with equals; that is,
Objects.equal(a, b)implies thatpredicate.apply(a) == predicate.apply(b)).
-
containsAll
public boolean containsAll(java.lang.Iterable<? extends C> values)
-
encloses
public boolean encloses(Range<C> other)
Returnstrueif the bounds ofotherdo not extend outside the bounds of this range. Examples:[3..6]encloses[4..5](3..6)encloses(3..6)[3..6]encloses[4..4)(even though the latter is empty)(3..6]does not enclose[3..6][4..5]does not enclose(3..6)(even though it contains every value contained by the latter range)[3..6]does not enclose(1..1](even though it contains every value contained by the latter range)
Note that if
a.encloses(b), thenb.contains(v)impliesa.contains(v), but as the last two examples illustrate, the converse is not always true.Being reflexive, antisymmetric and transitive, the
enclosesrelation defines a partial order over ranges. There exists a unique maximal range according to this relation, and also numerous minimal ranges. Enclosure also implies connectedness.
-
isConnected
public boolean isConnected(Range<C> other)
Returnstrueif there exists a (possibly empty) range which is enclosed by both this range andother.For example,
[2, 4)and[5, 7)are not connected[2, 4)and[3, 5)are connected, because both enclose[3, 4)[2, 4)and[4, 6)are connected, because both enclose the empty range[4, 4)
Note that this range and
otherhave a well-defined union and intersection (as a single, possibly-empty range) if and only if this method returnstrue.The connectedness relation is both reflexive and symmetric, but does not form an equivalence relation as it is not transitive.
Note that certain discrete ranges are not considered connected, even though there are no elements "between them." For example,
[3, 5]is not considered connected to[6, 10]. In these cases, it may be desirable for both input ranges to be preprocessed withcanonical(DiscreteDomain)before testing for connectedness.
-
intersection
public Range<C> intersection(Range<C> connectedRange)
Returns the maximal range enclosed by both this range andconnectedRange, if such a range exists.For example, the intersection of
[1..5]and(3..7)is(3..5]. The resulting range may be empty; for example,[1..5)intersected with[5..7)yields the empty range[5..5).The intersection exists if and only if the two ranges are connected.
The intersection operation is commutative, associative and idempotent, and its identity element is
all()).- Throws:
java.lang.IllegalArgumentException- ifisConnected(connectedRange)isfalse
-
gap
public Range<C> gap(Range<C> otherRange)
Returns the maximal range lying between this range andotherRange, if such a range exists. The resulting range may be empty if the two ranges are adjacent but non-overlapping.For example, the gap of
[1..5]and(7..10)is(5..7]. The resulting range may be empty; for example, the gap between[1..5)[5..7)yields the empty range[5..5).The gap exists if and only if the two ranges are either disconnected or immediately adjacent (any intersection must be an empty range).
The gap operation is commutative.
- Throws:
java.lang.IllegalArgumentException- if this range andotherRangehave a nonempty intersection- Since:
- 27.0
-
span
public Range<C> span(Range<C> other)
Returns the minimal range that encloses both this range andother. For example, the span of[1..3]and(5..7)is[1..7).If the input ranges are connected, the returned range can also be called their union. If they are not, note that the span might contain values that are not contained in either input range.
Like
intersection, this operation is commutative, associative and idempotent. Unlike it, it is always well-defined for any two input ranges.
-
canonical
public Range<C> canonical(DiscreteDomain<C> domain)
Returns the canonical form of this range in the given domain. The canonical form has the following properties:- equivalence:
a.canonical().contains(v) == a.contains(v)for allv(in other words,ContiguousSet.create(a.canonical(domain), domain).equals( ContiguousSet.create(a, domain)) - uniqueness: unless
a.isEmpty(),ContiguousSet.create(a, domain).equals(ContiguousSet.create(b, domain))impliesa.canonical(domain).equals(b.canonical(domain)) - idempotence:
a.canonical(domain).canonical(domain).equals(a.canonical(domain))
Furthermore, this method guarantees that the range returned will be one of the following canonical forms:
- [start..end)
- [start..+∞)
- (-∞..end) (only if type
Cis unbounded below) - (-∞..+∞) (only if type
Cis unbounded below)
- equivalence:
-
equals
public boolean equals(@CheckForNull java.lang.Object object)
Returnstrueifobjectis a range having the same endpoints and bound types as this range. Note that discrete ranges such as(1..4)and[2..3]are not equal to one another, despite the fact that they each contain precisely the same set of values. Similarly, empty ranges are not equal unless they have exactly the same representation, so[3..3),(3..3],(4..4]are all unequal.
-
hashCode
public int hashCode()
Returns a hash code for this range.- Overrides:
hashCodein classjava.lang.Object
-
toString
public java.lang.String toString()
Returns a string representation of this range, such as"[3..5)"(other examples are listed in the class documentation).- Overrides:
toStringin classjava.lang.Object
-
-