On Thu, 21 Feb 2002 [EMAIL PROTECTED] 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:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to