MATH-259 - check for Comparable when adding values

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@765996 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Sebastian Bazley 2009-04-17 13:34:59 +00:00
parent 04d470232e
commit aa13ac4d77
2 changed files with 34 additions and 1 deletions

View File

@ -101,9 +101,26 @@ public class Frequency implements Serializable {
* </p>
*
* @param v the value to add.
* @throws IllegalArgumentException if <code>v</code> is not comparable.
* @throws IllegalArgumentException if <code>v</code> is not comparable with previous entries
* @throws ClassCastException if <code>v</code> is not Comparable
* @deprecated use {@link #addValue(Comparable)} instead
*/
@Deprecated
public void addValue(Object v) {
addValue((Comparable<?>) v);
}
/**
* Adds 1 to the frequency count for v.
* <p>
* If other objects have already been added to this Frequency, v must
* be comparable to those that have already been added.
* </p>
*
* @param v the value to add.
* @throws IllegalArgumentException if <code>v</code> is not comparable with previous entries
*/
public void addValue(Comparable<?>v){
Object obj = v;
if (v instanceof Integer) {
obj = Long.valueOf(((Integer) v).longValue());

View File

@ -189,6 +189,22 @@ public final class FrequencyTest extends TestCase {
}
}
// Check what happens when non-Comparable objects are added
public void testAddNonComparable(){
try {
f.addValue(new Object()); // This was OK
fail("Expected ClassCastException");
} catch (ClassCastException expected) {
}
f.clear();
f.addValue(1);
try {
f.addValue(new Object());
fail("Expected ClassCastException"); // Previously would have been IllegalArgument
} catch (ClassCastException expected) {
}
}
/** test empty table */
public void testEmptyTable() {
assertEquals("freq sum, empty table", 0, f.getSumFreq());