01: /*
02: * Copyright 2002-2005 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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:
17: package org.springframework.util.comparator;
18:
19: import java.io.Serializable;
20: import java.util.Comparator;
21:
22: /**
23: * A Comparator for Boolean objects that can sort either true or false first.
24: *
25: * @author Keith Donald
26: * @since 1.2.2
27: */
28: public final class BooleanComparator implements Comparator,
29: Serializable {
30:
31: /**
32: * A shared default instance of this comparator, treating true lower
33: * than false.
34: */
35: public static final BooleanComparator TRUE_LOW = new BooleanComparator(
36: true);
37:
38: /**
39: * A shared default instance of this comparator, treating true higher
40: * than false.
41: */
42: public static final BooleanComparator TRUE_HIGH = new BooleanComparator(
43: false);
44:
45: private final boolean trueLow;
46:
47: /**
48: * Create a BooleanComparator that sorts boolean values based on
49: * the provided flag.
50: * <p>Alternatively, you can use the default shared instances:
51: * <code>BooleanComparator.TRUE_LOW</code> and
52: * <code>BooleanComparator.TRUE_HIGH</code>.
53: * @param trueLow whether to treat true as lower or higher than false
54: * @see #TRUE_LOW
55: * @see #TRUE_HIGH
56: */
57: public BooleanComparator(boolean trueLow) {
58: this .trueLow = trueLow;
59: }
60:
61: public int compare(Object o1, Object o2) {
62: boolean v1 = ((Boolean) o1).booleanValue();
63: boolean v2 = ((Boolean) o2).booleanValue();
64: return (v1 ^ v2) ? ((v1 ^ this .trueLow) ? 1 : -1) : 0;
65: }
66:
67: public boolean equals(Object obj) {
68: if (this == obj) {
69: return true;
70: }
71: if (!(obj instanceof BooleanComparator)) {
72: return false;
73: }
74: return (this .trueLow == ((BooleanComparator) obj).trueLow);
75: }
76:
77: public int hashCode() {
78: return (this .trueLow ? -1 : 1) * getClass().hashCode();
79: }
80:
81: public String toString() {
82: return "BooleanComparator: "
83: + (this .trueLow ? "true low" : "true high");
84: }
85:
86: }
|