bayard 02/02/20 22:02:56
Modified: util/src/java/org/apache/commons/util/compare
ComparableComparator.java
Log:
Changed at Michael Smith's warning to have the same behaviour if an
object passed in is not a Comparable. The behaviour is that it will
fire off an IllegalArgumentException. The Message in this is different,
but I'm hoping that is not a biggy in the contract for same behaviour.
I also made it so it considers either one being null to be an
IllegalArgumentException. Up for debate.
Reviewed by:Michael A. Smith
Revision Changes Path
1.2 +32 -3
jakarta-commons-sandbox/util/src/java/org/apache/commons/util/compare/ComparableComparator.java
Index: ComparableComparator.java
===================================================================
RCS file:
/home/cvs/jakarta-commons-sandbox/util/src/java/org/apache/commons/util/compare/ComparableComparator.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- ComparableComparator.java 21 Feb 2002 05:04:01 -0000 1.1
+++ ComparableComparator.java 21 Feb 2002 06:02:56 -0000 1.2
@@ -59,9 +59,11 @@
/**
* A Comparator that compares Comparable objects.
+ * Throws IllegalArgumentExceptions if the objects are not
+ * Comparable, or if they are null.
*
* @author [EMAIL PROTECTED]
- * @version $Id: ComparableComparator.java,v 1.1 2002/02/21 05:04:01 bayard Exp $
+ * @version $Id: ComparableComparator.java,v 1.2 2002/02/21 06:02:56 bayard Exp $
*/
public class ComparableComparator implements Comparator {
@@ -69,10 +71,37 @@
}
public int compare(Object o1, Object o2) {
+ if( (o1 == null) || (o2 == null) ) {
+ throw new IllegalArgumentException(
+ "There were nulls in the arguments for this method: "+
+ "compare("+o1 + ", " + o2 + ")"
+ );
+ }
+
if(o1 instanceof Comparable) {
- return ((Comparable)o1).compareTo(o2);
+ if(o2 instanceof Comparable) {
+ return ((Comparable)o1).compareTo(o2);
+ } else {
+ // o2 wasn't comparable
+ throw new IllegalArgumentException(
+ "The first argument of this method was not a Comparable: " +
+ o2.getClass().getName()
+ );
+ }
+ } else
+ if(o2 instanceof Comparable) {
+ // o1 wasn't comparable
+ throw new IllegalArgumentException(
+ "The second argument of this method was not a Comparable: " +
+ o1.getClass().getName()
+ );
+ } else {
+ // neither were comparable
+ throw new IllegalArgumentException(
+ "Both arguments of this method were not Comparables: " +
+ o1.getClass().getName() + " and " + o2.getClass().getName()
+ );
}
- return 0;
}
}
--
To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>