import java.util.Comparator;

/**
 * Used for sorting rows in a table.
 * Callback delegate to describe our particular collating sequence
 * to SunSort, binary search etc.
 * Objects at each grid point can be many
 * different types so long as they implement the Comparable interface,
 * and all objects in a column are of the same type.
 */
public class MultiColumnComparator implements Comparator
   {
   /**
   * List of columns we will sort, major key first,
   * 0-based.
   */
   private int[] colsToSort;

   /**
   * Do we sort the i'th most important column in ascending or
   * descending order. true=ascending.
   */
   private boolean[] ascendingOnCol;

   /**
   * public constructor
   *
   * @param colsToSort 0-based cols to sort. May not be null or empty.
   * Specify most important (major) key first and tie breakers later.
   * @param ascendingOncol. 0-based booleans how to sort each column you requested
   * to be sorted in that same order (Don't include non-sort-key columns).
   * true=ascending, false=descending. Array will always have same length as colsToSort.
   */
   public MultiColumnComparator (int[] colsToSort, boolean [] ascendingOnCol)
      {
      if ( colsToSort.length != ascendingOnCol.length )
         {
         throw new IllegalArgumentException( "wrong length on MulticolumnComparator parms" );
         }this.colsToSort = colsToSort;
      this.ascendingOnCol = ascendingOnCol;
      }

   /** Compare two rows.
    * effectively returns a-b;
    * e.g. +1 (or any +ve number) if a > b
    * 0 if a == b
    * -1 (or any -ve number) if a < b
    */
   public final int compare ( Object a , Object b )
      {
      Object[] rowa = (Object [])a;
      Object[] rowb = (Object [])b;

      for ( int i=0; i<colsToSort.length; i++ )
         {
         int col = colsToSort[i];
         int result = ((Comparable) rowa [col] ).compareTo ( rowb[col]);
         if ( result != 0 )
            {
            if ( ascendingOnCol [i] ) return result;
            else return -result;
            }
         }// end for // everything was exactly equal
      return 0;
      } // end compare

   } // end class MultiColumnComparator