1 16 17 package org.springframework.util.comparator; 18 19 import java.util.Comparator ; 20 21 import org.springframework.util.Assert; 22 23 32 public class NullSafeComparator implements Comparator { 33 34 38 public static final NullSafeComparator NULLS_LOW = new NullSafeComparator(true); 39 40 44 public static final NullSafeComparator NULLS_HIGH = new NullSafeComparator(false); 45 46 47 private final Comparator nonNullComparator; 48 49 private final boolean nullsLow; 50 51 52 66 private NullSafeComparator(boolean nullsLow) { 67 this(new ComparableComparator(), nullsLow); 68 } 69 70 79 public NullSafeComparator(Comparator comparator, boolean nullsLow) { 80 Assert.notNull(comparator, "The non-null comparator is required"); 81 this.nonNullComparator = comparator; 82 this.nullsLow = nullsLow; 83 } 84 85 86 public int compare(Object o1, Object o2) { 87 if (o1 == o2) { 88 return 0; 89 } 90 if (o1 == null) { 91 return (this.nullsLow ? -1 : 1); 92 } 93 if (o2 == null) { 94 return (this.nullsLow ? 1 : -1); 95 } 96 return this.nonNullComparator.compare(o1, o2); 97 } 98 99 public boolean equals(Object obj) { 100 if (this == obj) { 101 return true; 102 } 103 if (!(obj instanceof NullSafeComparator)) { 104 return false; 105 } 106 NullSafeComparator other = (NullSafeComparator) obj; 107 return (this.nonNullComparator.equals(other.nonNullComparator) && this.nullsLow == other.nullsLow); 108 } 109 110 public int hashCode() { 111 return (this.nullsLow ? -1 : 1) * this.nonNullComparator.hashCode(); 112 } 113 114 public String toString() { 115 return "NullSafeComparator: non-null comparator [" + this.nonNullComparator + "]; " + 116 (this.nullsLow ? "nulls low" : "nulls high"); 117 } 118 119 } 120 | Popular Tags |