001/*002 * Copyright 2002-2012 the original author or authors.003 *004 * Licensed under the Apache License, Version 2.0 (the "License");005 * you may not use this file except in compliance with the License.006 * You may obtain a copy of the License at007 *008 * https://www.apache.org/licenses/LICENSE-2.0009 *010 * Unless required by applicable law or agreed to in writing, software011 * distributed under the License is distributed on an "AS IS" BASIS,012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.013 * See the License for the specific language governing permissions and014 * limitations under the License.015 */016017package org.springframework.util.comparator;018019import java.util.Comparator;020021import org.springframework.util.Assert;022023/**024 * A Comparator that will safely compare nulls to be lower or higher than025 * other objects. Can decorate a given Comparator or work on Comparables.026 *027 * @author Keith Donald028 * @author Juergen Hoeller029 * @since 1.2.2030 * @see Comparable031 */032public class NullSafeComparator<T> implements Comparator<T> {033034 /**035 * A shared default instance of this comparator, treating nulls lower036 * than non-null objects.037 */038 @SuppressWarnings("rawtypes")039 public static final NullSafeComparator NULLS_LOW = new NullSafeComparator<Object>(true);040041 /**042 * A shared default instance of this comparator, treating nulls higher043 * than non-null objects.044 */045 @SuppressWarnings("rawtypes")046 public static final NullSafeComparator NULLS_HIGH = new NullSafeComparator<Object>(false);047048 private final Comparator<T> nonNullComparator;049050 private final boolean nullsLow;051052053 /**054 * Create a NullSafeComparator that sorts {@code null} based on055 * the provided flag, working on Comparables.056 * <p>When comparing two non-null objects, their Comparable implementation057 * will be used: this means that non-null elements (that this Comparator058 * will be applied to) need to implement Comparable.059 * <p>As a convenience, you can use the default shared instances:060 * {@code NullSafeComparator.NULLS_LOW} and061 * {@code NullSafeComparator.NULLS_HIGH}.062 * @param nullsLow whether to treat nulls lower or higher than non-null objects063 * @see Comparable064 * @see #NULLS_LOW065 * @see #NULLS_HIGH066 */067 @SuppressWarnings({ "unchecked", "rawtypes"})068 private NullSafeComparator(boolean nullsLow) {069 this.nonNullComparator = new ComparableComparator();070 this.nullsLow = nullsLow;071 }072073 /**074 * Create a NullSafeComparator that sorts {@code null} based on the075 * provided flag, decorating the given Comparator.076 * <p>