commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Michael A. Smith" <mich...@iammichael.org>
Subject Re: cvs commit: jakarta-commons-sandbox/util/src/java/org/apache/commons/util/compare ComparableComparator.java
Date Thu, 21 Feb 2002 05:57:19 GMT
On Thu, 21 Feb 2002 bayard@generationjava.com wrote:
> Sounds valid. As far as the contract goes, how about if a
> class-cast-exception is thrown in both cases, or if another 'illegal
> input' decision is taken, ie) returning 0.

Yup.  I'd be fine with:

  int compare(Object o1, Object o2) {
    return ((Comparable)o1).compareTo((Comparable)o2);
  }

With that, you're placing the burden on the comparable object to ensure it 
implements the compareTo method with regards to the Comparable contract, 
rather than keeping the burden of the Comparator contract.  Then, it's not 
your problem.  :)

If you really want to be paranoid, you could do both and make sure they 
return inverses:

  int compare(Object o1, Object o2) {
    int result1 = ((Comparable)o1).compareTo(o2);
    int result2 = ((Comparable)o2).compareTo(o1);

    if(result1 == 0 && result2 == 0) return 0;
    if(result1 < 0 && result2 > 0) return -1;
    if(result1 > 0 && result2 < 0) return 1;
 
    // results inconsistent
    throw new ClassCastException("o1 not comparable to o2");
  }

that may be a bit too paranoid though.

> As for its use, consider the following code:

yeah, that's how I figured it would be used.  :)

regards,
Michael



--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message