CompareNullSafe.java

  1. /*******************************************************************************
  2.  * Copyright 2013 André Rouél
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *   http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  ******************************************************************************/
  16. package net.sf.uadetector.internal.util;

  17. import java.io.Serializable;
  18. import java.util.Comparator;

  19. /**
  20.  * Compares two references to each other and {@code null} is assumed to be less than a non-{@code null} value. This
  21.  * class provides the first check for null safe comparison.
  22.  *
  23.  * @author André Rouél
  24.  */
  25. public abstract class CompareNullSafe<T> implements Comparator<T>, Serializable {

  26.     private static final long serialVersionUID = -704997500621650775L;

  27.     /**
  28.      * Compares to integers.
  29.      *
  30.      * @param a
  31.      *            first integer
  32.      * @param b
  33.      *            second integer
  34.      * @return {@code -1} if {@code a} is less, {@code 0} if equal, or {@code 1} if greater than {@code b}
  35.      */
  36.     public static int compareInt(final int a, final int b) {
  37.         return a > b ? 1 : a == b ? 0 : -1;
  38.     }

  39.     /**
  40.      * Compares two objects null safe to each other.
  41.      *
  42.      * @param o1
  43.      *            the first reference
  44.      * @param o2
  45.      *            the second reference
  46.      * @return a negative value if o1 < o2, zero if o1 = o2 and a positive value if o1 > o2
  47.      */
  48.     @Override
  49.     public int compare(final T o1, final T o2) {
  50.         int result = 0;
  51.         if (o1 == null) {
  52.             if (o2 != null) {
  53.                 result = -1;
  54.             }
  55.         } else if (o2 == null) {
  56.             result = 1;
  57.         } else {
  58.             result = compareType(o1, o2);
  59.         }
  60.         return result;
  61.     }

  62.     public abstract int compareType(final T o1, final T o2);

  63. }