[LANG-726] Add a method e.g. Range<T> Range<T>.intersectionWith(Range<T>)

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@1147537 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Matthew Jason Benson 2011-07-17 06:10:37 +00:00
parent 6c65862a68
commit 2e072c1da8
2 changed files with 41 additions and 0 deletions

View File

@ -371,6 +371,26 @@ public final class Range<T> implements Serializable {
return isBefore(otherRange.minimum);
}
/**
* Calculate the intersection of {@code this} and an overlapping Range.
* @param other overlapping Range
* @return range representing the intersection of {@code this} and {@code other} ({@code this} if equal)
* @throws IllegalArgumentException if {@code other} does not overlap {@code this}
* @since 3.0.1
*/
public Range<T> intersectionWith(Range<T> other) {
if (!this.isOverlappedBy(other)) {
throw new IllegalArgumentException(String.format(
"Cannot calculate intersection with non-overlapping range %s", other));
}
if (this.equals(other)) {
return this;
}
T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum;
T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum;
return between(min, max, getComparator());
}
// Basics
//--------------------------------------------------------------------

View File

@ -342,6 +342,27 @@ public class RangeTest {
assertFalse(intRange.isBeforeRange(Range.between(10, 20)));
}
@Test
public void testIntersectionWith() {
assertSame(intRange, intRange.intersectionWith(intRange));
assertSame(byteRange, byteRange.intersectionWith(byteRange));
assertSame(longRange, longRange.intersectionWith(longRange));
assertSame(floatRange, floatRange.intersectionWith(floatRange));
assertSame(doubleRange, doubleRange.intersectionWith(doubleRange));
assertEquals(Range.between(10, 15), intRange.intersectionWith(Range.between(5, 15)));
}
@Test(expected = IllegalArgumentException.class)
public void testIntersectionWithNull() {
intRange.intersectionWith(null);
}
@Test(expected = IllegalArgumentException.class)
public void testIntersectionWithNonOverlapping() {
intRange.intersectionWith(Range.between(0, 9));
}
//-----------------------------------------------------------------------
@Test
public void testSerializing() {