CompareUtil.java

  1. package gov.usgs.earthquake.util;

  2. /**
  3.  * Utility class for comparing potentially null values.
  4.  */
  5. public class CompareUtil {

  6.     /**
  7.      * A method to simplify comparison of two values, either of which may be
  8.      * null.
  9.      *
  10.      * For purposes of this comparison, null values are > non-null values.
  11.      *
  12.      * @param a
  13.      *            value to compare
  14.      * @param b
  15.      *            value to compare
  16.      * @param <T>
  17.      *            type
  18.      * @return -1, if a is not null and b is null; 0, if a is null and b is
  19.      *         null; 1, if a is null and b is not null; otherwise,
  20.      *         a.compareTo(b).
  21.      */
  22.     public static <T extends Comparable<T>> int nullSafeCompare(final T a, final T b) {
  23.         if (a == null && b != null) {
  24.             // null > real values
  25.             return 1;
  26.         } else if (a != null && b == null) {
  27.             // real values < null
  28.             return -1;
  29.         } else if (a == null && b == null) {
  30.             // null == null
  31.             return 0;
  32.         } else {
  33.             // not null, use object compareTo
  34.             return a.compareTo(b);
  35.         }
  36.     }

  37. }