Adding elementCompareTo method as requested in LANG-386 (which called the method positionOfXxx)

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@835777 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Henri Yandell 2009-11-13 08:51:08 +00:00
parent 4c124cea28
commit 452a6c0cd8
2 changed files with 39 additions and 0 deletions

View File

@ -199,6 +199,30 @@ public class Range<T> {
return this.comparator.compare(element, getMaximum()) > 0;
}
/**
* <p>Tests where the specified element occurs relative to this range.</p>
* <p>The API is reminiscent of the Comparable interface returning <code>-1</code> if
* the element is before the range, <code>0</code> if contained within the range and
* <code>1</code> if the element is after the range. </p>
*
* @param element the element to test
* @return -1, 0 or +1 depending on the element's location relative to the range
*/
public int elementCompareTo(T element) {
if(element == null) {
// Comparable API says throw NPE on null
throw new NullPointerException("Element is null");
}
if(elementBefore(element)) {
return -1;
} else
if(elementAfter(element)) {
return 1;
} else {
return 0;
}
}
// Range tests
//--------------------------------------------------------------------

View File

@ -146,6 +146,21 @@ public class RangeTest extends TestCase {
assertTrue(intRange.elementAfter(25));
}
public void testElementCompareTo() {
try {
intRange.elementCompareTo(null);
fail("NullPointerException should have been thrown");
} catch(NullPointerException npe) {
// expected
}
assertEquals(-1, intRange.elementCompareTo(5));
assertEquals(0, intRange.elementCompareTo(10));
assertEquals(0, intRange.elementCompareTo(15));
assertEquals(0, intRange.elementCompareTo(20));
assertEquals(1, intRange.elementCompareTo(25));
}
// --------------------------------------------------------------------------
public void testContainsRange() {