1 package com.jofti.util; 2 3 import java.util.ArrayList ; 4 import java.util.Comparator ; 5 import java.util.List ; 6 7 public class CompositeComparator implements Comparator { 8 9 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)).isReversed(); 31 } 32 return false; 33 } 34 35 public Comparator getComparator(int index){ 36 return (Comparator )comparators.get(index); 37 } 38 public int compare(Object arg0, Object 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 { 63 64 public Comparator comp =null; 65 boolean reverse =false; 66 67 public ComparatorWrapper(Comparator comp, boolean reverse){ 68 this.comp=comp; 69 this.reverse=reverse; 70 } 71 public int compare(Object o1, Object o2) { 72 return comp.compare(o1,o2); 74 } 75 76 boolean isReversed(){ 77 return reverse; 78 } 79 80 } 81 82 } 83 | Popular Tags |