diff --git a/src/java/org/apache/commons/lang/Range.java b/src/java/org/apache/commons/lang/Range.java index abfe5f248..667f2a682 100644 --- a/src/java/org/apache/commons/lang/Range.java +++ b/src/java/org/apache/commons/lang/Range.java @@ -199,6 +199,30 @@ public class Range { return this.comparator.compare(element, getMaximum()) > 0; } + /** + *

Tests where the specified element occurs relative to this range.

+ *

The API is reminiscent of the Comparable interface returning -1 if + * the element is before the range, 0 if contained within the range and + * 1 if the element is after the range.

+ * + * @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 //-------------------------------------------------------------------- diff --git a/src/test/org/apache/commons/lang/RangeTest.java b/src/test/org/apache/commons/lang/RangeTest.java index b9418e740..805cfac10 100644 --- a/src/test/org/apache/commons/lang/RangeTest.java +++ b/src/test/org/apache/commons/lang/RangeTest.java @@ -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() {