public class Range extends Object implements Comparable<Range>
minimum
value and a maximum
value.
Range objects always ensure that the following class invariant is true:
minimum <= maximum
Constructor and Description |
---|
Range()
Initialize this range with minimum value -1 and a maximum value 1.
|
Range(int min,
int max)
Initialize this range with the specified minimum and maximum values.
|
Modifier and Type | Method and Description |
---|---|
int |
compareTo(Range other)
Compares this range to another range.
|
boolean |
contains(int value)
Checks if
value is inside this range. |
int |
getMaximum()
Returns the maximum value of the range
|
int |
getMinimum()
Returns the minimum value of the range
|
Range |
intersect(Range other)
Returns a new range formed by the intersection of this range and the
specified range.
|
boolean |
overlaps(Range other)
Checks if this range overlaps with another range.
|
String |
toString()
Returns the string representation of a range.
|
long |
width()
Returns the width of this range (the maximum value minus the minimum
value).
|
public Range()
public Range(int min, int max)
min
- the minimum value of the rangemax
- the maximum value of the rangeIllegalArgumentException
- if min is greater than maxmin <= max
public int getMinimum()
public int getMaximum()
public long width()
public boolean contains(int value)
value
is inside this range. A value is considered
inside this range if the value is greater than or equal to the minimum
value of this range and value is less than or equal to the maximum
value of this range.value
- the value to checkpublic boolean overlaps(Range other)
int
value is contained by both ranges. For example,
the two ranges
[0, 5]
and [4, 10]
overlap because all values between
4
and 5
are contained by both ranges.
The two ranges
[0, 5]
and [5, 8]
overlap because both ranges
contain the value 5
other
- the other range to checkpublic Range intersect(Range other)
[0, 5]
and [4, 10]
is the range [4, 5]
.
The range [0, 0]
is returned if the two ranges do not overlap.
other
- the range to intersect with this rangepublic int compareTo(Range other)
Returns -1 if this range lies completely to the left of the other range. For example, the range [0, 1] lies completely to the left of the range [2, 10].
Returns 1 if this range lies completely to the right of the other range. For example, the range [10, 11] lies completely to the left of the range [2, 9].
Returns 0 if both ranges contain at least one common value. For example, the range [10, 11] shares one common value with the range [11, 15] (the number 11).
compareTo
in interface Comparable<Range>
other
- the range to comparepublic String toString()
[2, 25]
represents the range whose minimum value is 2
and whose
maximum value is 25