commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Antony Riley <ant...@cyberiantiger.org>
Subject Re: ObjectUtils.compare
Date Tue, 11 Aug 2009 10:06:57 GMT
My motivation for the addition was for exactly one reason, writing null safe
comparators.

The facility exists already in collections via

ComparatorUtils.nullLowComparator(Comparator c)
ComparatorUtils.nullHighComparator(Comparator c)

I just failed to find it.

-Antony

On Tue, Aug 11, 2009 at 9:13 AM, Henri Yandell <flamefew@gmail.com> wrote:

> Maybe something for the CompareUtils class proposed in LANG-483:
>
>  http://issues.apache.org/jira/browse/LANG-483
>
> I'd prefer compareNullFirst, compareNullLast instead of the boolean param.
>
> Hen
>
> On Mon, Aug 10, 2009 at 5:23 AM, Antony Riley<antony@cyberiantiger.org>
> wrote:
> > Maybe I'm missing something obvious but commons lang does not seem to
> > provide a null safe compare method for comparable objects.
> >
> > My apologies if this functionality exists somewhere in commons lang and
> I'm
> > being brain dead with regards to locating it.
> >
> > It seems like a really obvious addition, code would probably look like
> >
> > // In ObjectUtils.
> >
> > /**
> >  * Compare two Comparable objects for order.
> >  *
> >  * This method is null safe. Null is considered to be less than all other
> > objects.
> >  *
> >  * @param a the first object to be compared.
> >  * @param b the second object to be compared.
> >  * @return a negative integer, zero, or a positive integer as the first
> > argument is less than, equal to, or greater than the second.
> >  */
> > public int compare(Comparable a, Comparable b) {
> >    return compare(a,b,true);
> > }
> >
> > /**
> >  * Compare two Comparable objects for order.
> >  *
> >  * This method is null safe. Null is considered to be less than all other
> > objects if nullfirst is true, else
> >  * it is considered to be greater than all other objects.
> >  *
> >  * @param a the first object to be compared.
> >  * @param b the second object to be compared.
> >  * @param nullfirst
> >  * @return a negative integer, zero, or a positive integer as the first
> > argument is less than, equal to, or greater than the second.
> >  */
> > public int compare(Comparable a, Comparable b, boolean nullfirst) {
> >    // Deal with the case both a, b are null or they are both equal first.
> >    if (a == b) {
> >        return 0;
> >    } else if (a == null) {
> >        return nullfirst ? -1 : 1;
> >    } else if (b == null) {
> >        return nullfirst ? 1 : -1;
> >    } else {
> >        return a.compareTo(b);
> >    }
> > }
> >
> > -Antony
> >
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: dev-unsubscribe@commons.apache.org
> For additional commands, e-mail: dev-help@commons.apache.org
>
>

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message