1 16 17 package org.springframework.util.comparator; 18 19 import java.io.Serializable ; 20 import java.util.Comparator ; 21 22 31 public class InvertibleComparator implements Comparator , Serializable { 32 33 private final Comparator comparator; 34 35 private boolean ascending = true; 36 37 38 43 public InvertibleComparator(Comparator comparator) { 44 this.comparator = comparator; 45 } 46 47 53 public InvertibleComparator(Comparator comparator, boolean ascending) { 54 this.comparator = comparator; 55 setAscending(ascending); 56 } 57 58 59 62 public void setAscending(boolean ascending) { 63 this.ascending = ascending; 64 } 65 66 69 public boolean isAscending() { 70 return ascending; 71 } 72 73 77 public void invertOrder() { 78 this.ascending = !this.ascending; 79 } 80 81 82 public int compare(Object o1, Object o2) { 83 int result = this.comparator.compare(o1, o2); 84 if (result != 0) { 85 if (!this.ascending) { 87 if (Integer.MIN_VALUE == result) { 88 result = Integer.MAX_VALUE; 89 } 90 else { 91 result *= -1; 92 } 93 } 94 return result; 95 } 96 return 0; 97 } 98 99 public boolean equals(Object obj) { 100 if (this == obj) { 101 return true; 102 } 103 if (!(obj instanceof InvertibleComparator)) { 104 return false; 105 } 106 InvertibleComparator other = (InvertibleComparator) obj; 107 return (this.comparator.equals(other.comparator) && this.ascending == other.ascending); 108 } 109 110 public int hashCode() { 111 return this.comparator.hashCode(); 112 } 113 114 public String toString() { 115 return "InvertibleComparator: [" + this.comparator + "]; ascending=" + this.ascending; 116 } 117 118 } 119 | Popular Tags |