KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jofti > util > CompositeComparator


1 package com.jofti.util;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.Comparator JavaDoc;
5 import java.util.List JavaDoc;
6
7 public class CompositeComparator implements Comparator JavaDoc {
8
9     List JavaDoc comparators = new ArrayList JavaDoc();
10     
11     public void addComparator(Comparator JavaDoc comp){
12         doAdd(comp,false);
13     }
14     
15     public void addComparator(Comparator JavaDoc comp,boolean reverse){
16         doAdd(comp,reverse);
17     }
18     
19     private void doAdd(Comparator JavaDoc 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)).isReversed();
31         }
32         return false;
33     }
34     
35     public Comparator JavaDoc getComparator(int index){
36         return (Comparator JavaDoc)comparators.get(index);
37     }
38     public int compare(Object JavaDoc arg0, Object JavaDoc arg1) {
39         
40         for (int i=0;i<comparators.size();i++){
41             ComparatorWrapper comp = (ComparatorWrapper)comparators.get(i);
42             
43             
44             int val = comp.compare(arg0,arg1);
45             
46             if (val !=0){
47                 if (comp.isReversed()){
48                     if(Integer.MIN_VALUE == val) {
49                         val = Integer.MAX_VALUE;
50                     } else {
51                         val *= -1;
52                     }
53                 }
54                 return val;
55             }
56             
57         }
58         return 0;
59         
60     }
61     
62     class ComparatorWrapper implements Comparator JavaDoc{
63
64         public Comparator JavaDoc comp =null;
65         boolean reverse =false;
66         
67         public ComparatorWrapper(Comparator JavaDoc comp, boolean reverse){
68             this.comp=comp;
69             this.reverse=reverse;
70         }
71         public int compare(Object JavaDoc o1, Object JavaDoc o2) {
72             // TODO Auto-generated method stub
73
return comp.compare(o1,o2);
74         }
75         
76         boolean isReversed(){
77             return reverse;
78         }
79         
80     }
81
82 }
83
Popular Tags