001/* 002 * Copyright 2002-2018 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 at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * 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 and 014 * limitations under the License. 015 */ 016 017package org.springframework.util.comparator; 018 019import java.io.Serializable; 020import java.util.Comparator; 021 022import org.springframework.lang.Nullable; 023 024/** 025 * A {@link Comparator} for {@link Boolean} objects that can sort either 026 * {@code true} or {@code false} first. 027 * 028 * @author Keith Donald 029 * @since 1.2.2 030 */ 031@SuppressWarnings("serial") 032public class BooleanComparator implements Comparator<Boolean>, Serializable { 033 034 /** 035 * A shared default instance of this comparator, 036 * treating {@code true} lower than {@code false}. 037 */ 038 public static final BooleanComparator TRUE_LOW = new BooleanComparator(true); 039 040 /** 041 * A shared default instance of this comparator, 042 * treating {@code true} higher than {@code false}. 043 */ 044 public static final BooleanComparator TRUE_HIGH = new BooleanComparator(false); 045 046 047 private final boolean trueLow; 048 049 050 /** 051 * Create a BooleanComparator that sorts boolean values based on 052 * the provided flag. 053 * <p>Alternatively, you can use the default shared instances: 054 * {@code BooleanComparator.TRUE_LOW} and 055 * {@code BooleanComparator.TRUE_HIGH}. 056 * @param trueLow whether to treat true as lower or higher than false 057 * @see #TRUE_LOW 058 * @see #TRUE_HIGH 059 */ 060 public BooleanComparator(boolean trueLow) { 061 this.trueLow = trueLow; 062 } 063 064 065 @Override 066 public int compare(Boolean v1, Boolean v2) { 067 return (v1 ^ v2) ? ((v1 ^ this.trueLow) ? 1 : -1) : 0; 068 } 069 070 071 @Override 072 public boolean equals(@Nullable Object other) { 073 return (this == other || (other instanceof BooleanComparator && 074 this.trueLow == ((BooleanComparator) other).trueLow)); 075 } 076 077 @Override 078 public int hashCode() { 079 return getClass().hashCode() * (this.trueLow ? -1 : 1); 080 } 081 082 @Override 083 public String toString() { 084 return "BooleanComparator: " + (this.trueLow ? "true low" : "true high"); 085 } 086 087}