1 16 package org.apache.commons.collections.comparators; 17 18 import java.io.Serializable ; 19 import java.util.Comparator ; 20 21 30 public class NullComparator implements Comparator , Serializable { 31 32 33 private static final long serialVersionUID = -5820772575483504339L; 34 35 38 private Comparator nonNullComparator; 39 40 44 private boolean nullsAreHigh; 45 46 53 public NullComparator() { 54 this(ComparableComparator.getInstance(), true); 55 } 56 57 70 public NullComparator(Comparator nonNullComparator) { 71 this(nonNullComparator, true); 72 } 73 74 86 public NullComparator(boolean nullsAreHigh) { 87 this(ComparableComparator.getInstance(), nullsAreHigh); 88 } 89 90 109 public NullComparator(Comparator nonNullComparator, boolean nullsAreHigh) { 110 this.nonNullComparator = nonNullComparator; 111 this.nullsAreHigh = nullsAreHigh; 112 113 if(nonNullComparator == null) { 114 throw new NullPointerException ("null nonNullComparator"); 115 } 116 } 117 118 135 public int compare(Object o1, Object o2) { 136 if(o1 == o2) { return 0; } 137 if(o1 == null) { return (this.nullsAreHigh ? 1 : -1); } 138 if(o2 == null) { return (this.nullsAreHigh ? -1 : 1); } 139 return this.nonNullComparator.compare(o1, o2); 140 } 141 142 149 public int hashCode() { 150 return (nullsAreHigh ? -1 : 1) * nonNullComparator.hashCode(); 151 } 152 153 164 public boolean equals(Object obj) { 165 if(obj == null) { return false; } 166 if(obj == this) { return true; } 167 if(!obj.getClass().equals(this.getClass())) { return false; } 168 169 NullComparator other = (NullComparator)obj; 170 171 return ((this.nullsAreHigh == other.nullsAreHigh) && 172 (this.nonNullComparator.equals(other.nonNullComparator))); 173 } 174 175 } 176 | Popular Tags |