01: package com.jofti.util;
02:
03: import java.util.ArrayList;
04: import java.util.Comparator;
05: import java.util.List;
06:
07: public class CompositeComparator implements Comparator {
08:
09: List comparators = new ArrayList();
10:
11: public void addComparator(Comparator comp) {
12: doAdd(comp, false);
13: }
14:
15: public void addComparator(Comparator comp, boolean reverse) {
16: doAdd(comp, reverse);
17: }
18:
19: private void doAdd(Comparator comp, boolean reverse) {
20: comparators.add(new ComparatorWrapper(comp, reverse));
21:
22: }
23:
24: public int getSize() {
25: return comparators.size();
26: }
27:
28: public boolean isReversed(int index) {
29: if (index < comparators.size()) {
30: return ((ComparatorWrapper) comparators.get(index))
31: .isReversed();
32: }
33: return false;
34: }
35:
36: public Comparator getComparator(int index) {
37: return (Comparator) comparators.get(index);
38: }
39:
40: public int compare(Object arg0, Object arg1) {
41:
42: for (int i = 0; i < comparators.size(); i++) {
43: ComparatorWrapper comp = (ComparatorWrapper) comparators
44: .get(i);
45:
46: int val = comp.compare(arg0, arg1);
47:
48: if (val != 0) {
49: if (comp.isReversed()) {
50: if (Integer.MIN_VALUE == val) {
51: val = Integer.MAX_VALUE;
52: } else {
53: val *= -1;
54: }
55: }
56: return val;
57: }
58:
59: }
60: return 0;
61:
62: }
63:
64: class ComparatorWrapper implements Comparator {
65:
66: public Comparator comp = null;
67: boolean reverse = false;
68:
69: public ComparatorWrapper(Comparator comp, boolean reverse) {
70: this .comp = comp;
71: this .reverse = reverse;
72: }
73:
74: public int compare(Object o1, Object o2) {
75: // TODO Auto-generated method stub
76: return comp.compare(o1, o2);
77: }
78:
79: boolean isReversed() {
80: return reverse;
81: }
82:
83: }
84:
85: }
|