/*
 * ParamCompare.java
 * 
 * Jim Frankenberger
 * USDA-ARS, West Lafayette IN
 * jrf@purdue.edu
 *
 * Created on September 23, 2004, 4:25 PM
 */

package ex1;
import java.io.Serializable;
import java.util.*;

/**
 * This class implements the comparator used in sorting columns.
 * It is sensitive to float strings and will convert the strings to float
 * values to do the compare if necessary.
 *
 * @author  jrf
 * @param <T>
 */
public class ParamCompare<T> implements Comparator<T>, Serializable {
    private static final long serialVersionUID = 1L;
    
    /** 
     * Creates a new instance of ParamCompare 
     */
    public ParamCompare() {
    }
    
    /**
     * Called automatically by a class using the comparator.
     * Converts strings to floats if necessary.
     * @param o1 First Object(string) to compare
     * @param o2 Second Object(string) to compare first against
     *
     * @return 0 if strings are equal, 1 if string 1 > string 2, -1 if string 1 < string 2
     */
    @Override
    public int compare(Object o1, Object o2) {
            
        String o1s = o1.toString();
        String o2s = o2.toString();

        if (o1s.equals(o2s))
            return 0;

        // Try to get a Float value out of this
        Float f1,f2;
        float f1v,f2v;
        try {
            f1 = Float.valueOf(o1s);
            f2 = Float.valueOf(o2s);

            if (f1.floatValue() > f2.floatValue())
                return 1;
            else if (f1.floatValue() < f2.floatValue())
                return -1;
            else
                return 0;
        }
        catch (NumberFormatException nfe) {
             return o1s.compareTo(o2s);
        }
           
    }
}
