All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dk.eobjects.metamodel.util.NumberComparator Maven / Gradle / Ivy

/**
 *  This file is part of MetaModel.
 *
 *  MetaModel is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MetaModel is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MetaModel.  If not, see .
 */
package dk.eobjects.metamodel.util;

import java.util.Comparator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math.MathException;
import org.apache.commons.math.util.DefaultTransformer;

/**
 * Comparator that can compare numbers of various kinds (short, integer, float,
 * double etc)
 */
public class NumberComparator implements Comparator {

	private static final Log _log = LogFactory.getLog(NumberComparator.class);
	private static Comparator _instance = new NumberComparator();

	public static Comparator getComparator() {
		return _instance;
	}

	private NumberComparator() {
	}

	public static Comparable getComparable(Object o) {
		try {
			final double n = new DefaultTransformer().transform(o);
			return new Comparable() {

				public int compareTo(Object o) {
					return _instance.compare(n, o);
				}

				@Override
				public String toString() {
					return "NumberComparable[number=" + n + "]";
				}

			};
		} catch (MathException e) {
			_log.error(e);
			throw new RuntimeException(e);
		}
	}

	public int compare(Object o1, Object o2) {
		try {
			double n1 = new DefaultTransformer().transform(o1);
			double n2 = new DefaultTransformer().transform(o2);
			return new Double(n1).compareTo(n2);
		} catch (MathException e) {
			_log.error(e);
			throw new RuntimeException(e);
		}
	}
}