bayard      02/02/20 22:16:32

  Modified:    util/src/java/org/apache/commons/util/compare
                        ComparableComparator.java
  Log:
  Made the class more paranoid by enforcing the Comparable interfaces
  contract that for objects o1 and o2, o1.compareTo(o2) and
  o2.compareTo(o1) must be inverses of each other, although the
  abs() of the value returned need not be the same it seems.
  Reviewed by:  Michael A. Smith
  
  Revision  Changes    Path
  1.3       +20 -2     
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.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- ComparableComparator.java 21 Feb 2002 06:02:56 -0000      1.2
  +++ ComparableComparator.java 21 Feb 2002 06:16:32 -0000      1.3
  @@ -61,9 +61,12 @@
    * A Comparator that compares Comparable objects.
    * Throws IllegalArgumentExceptions if the objects are not 
    * Comparable, or if they are null.
  + * Throws IllegalArgumentException if the compareTo of both 
  + * objects do not provide an inverse result of each other 
  + * as per the Comparable javadoc.
    *
    * @author [EMAIL PROTECTED]
  - * @version $Id: ComparableComparator.java,v 1.2 2002/02/21 06:02:56 bayard Exp $
  + * @version $Id: ComparableComparator.java,v 1.3 2002/02/21 06:16:32 bayard Exp $
    */
   public class ComparableComparator implements Comparator {
   
  @@ -80,7 +83,22 @@
           
           if(o1 instanceof Comparable) {
               if(o2 instanceof Comparable) {
  -                return ((Comparable)o1).compareTo(o2);
  +                int result1 = ((Comparable)o1).compareTo(o2);
  +                int result2 = ((Comparable)o2).compareTo(o1);
  +
  +                // enforce comparable contract
  +                if(result1 == 0 && result2 == 0) {
  +                    return 0;
  +                } else
  +                if(result1 < 0 && result2 > 0) {
  +                    return result1;
  +                } else
  +                if(result1 > 0 && result2 < 0) {
  +                    return result1;
  +                } else {
  +                    // results inconsistent
  +                    throw new IllegalArgumentException("o1 not comparable to o2");
  +                }
               } else {
                   // o2 wasn't comparable
                   throw new IllegalArgumentException(
  
  
  

--
To unsubscribe, e-mail:   <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to