1 43 44 package org.jfree.data; 45 46 import java.util.Comparator ; 47 48 import org.jfree.util.SortOrder; 49 50 54 public class KeyedValueComparator implements Comparator { 55 56 57 private KeyedValueComparatorType type; 58 59 60 private SortOrder order; 61 62 69 public KeyedValueComparator(KeyedValueComparatorType type, 70 SortOrder order) { 71 if (order == null) { 72 throw new IllegalArgumentException ("Null 'order' argument."); 73 } 74 this.type = type; 75 this.order = order; 76 } 77 78 83 public KeyedValueComparatorType getType() { 84 return this.type; 85 } 86 87 92 public SortOrder getOrder() { 93 return this.order; 94 } 95 96 105 public int compare(Object o1, Object o2) { 106 107 if (o2 == null) { 108 return -1; 109 } 110 if (o1 == null) { 111 return 1; 112 } 113 114 int result; 115 116 KeyedValue kv1 = (KeyedValue) o1; 117 KeyedValue kv2 = (KeyedValue) o2; 118 119 if (this.type == KeyedValueComparatorType.BY_KEY) { 120 if (this.order.equals(SortOrder.ASCENDING)) { 121 result = kv1.getKey().compareTo(kv2.getKey()); 122 } 123 else if (this.order.equals(SortOrder.DESCENDING)) { 124 result = kv2.getKey().compareTo(kv1.getKey()); 125 } 126 else { 127 throw new IllegalArgumentException ("Unrecognised sort order."); 128 } 129 } 130 else if (this.type == KeyedValueComparatorType.BY_VALUE) { 131 Number n1 = kv1.getValue(); 132 Number n2 = kv2.getValue(); 133 if (n2 == null) { 134 return -1; 135 } 136 if (n1 == null) { 137 return 1; 138 } 139 double d1 = n1.doubleValue(); 140 double d2 = n2.doubleValue(); 141 if (this.order.equals(SortOrder.ASCENDING)) { 142 if (d1 > d2) { 143 result = 1; 144 } 145 else if (d1 < d2) { 146 result = -1; 147 } 148 else { 149 result = 0; 150 } 151 } 152 else if (this.order.equals(SortOrder.DESCENDING)) { 153 if (d1 > d2) { 154 result = -1; 155 } 156 else if (d1 < d2) { 157 result = 1; 158 } 159 else { 160 result = 0; 161 } 162 } 163 else { 164 throw new IllegalArgumentException ("Unrecognised sort order."); 165 } 166 } 167 else { 168 throw new IllegalArgumentException ("Unrecognised type."); 169 } 170 171 return result; 172 } 173 174 } 175 | Popular Tags |