commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Antony Riley <ant...@cyberiantiger.org>
Subject ObjectUtils.compare
Date Mon, 10 Aug 2009 12:23:43 GMT
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

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