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

dk.eobjects.metamodel.util.ToStringComparator 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;

/**
 * Uses the toString method for comparison of objects
 */
public class ToStringComparator implements Comparator {

	private static Comparator _instance = new ToStringComparator();

	public static Comparator getComparator() {
		return _instance;
	}

	private ToStringComparator() {
	}

	public static Comparable getComparable(final Object o) {
		final String s = o.toString();
		return new Comparable() {

			public int compareTo(Object o2) {
				return _instance.compare(s, o2);
			}

			@Override
			public String toString() {
				return "ToStringComparable[string=" + s + "]";
			}
		};
	}

	public int compare(Object o1, Object o2) {
		if (o1 == null && o2 == null) {
			return -1;
		}
		if (o1 == null) {
			return -1;
		}
		if (o2 == null) {
			return 1;
		}
		return o1.toString().compareTo(o2.toString());
	}
}