Code Pretty Print Script

Thursday, November 7, 2013

Help! I have a Comparable but I need a Comparator

Are you tired of re-implementing a Comparator every time you encounter a Comparable? Regardless of whether you're working with String(s), Integer(s), Float(s) or "Anything"‽ else Comparable just use this ComparableComparator.

/*
 * Copyright © 2013 - Elliott Frisch
 * 
 * THIS SOFTWARE IS PROVIDED UNDER THE CREATIVE COMMONS
 * LICENSE 3.0 "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR
 * A PARTICULAR PURPOSE.
 * 
 * To use this software you must agree to the complete
 * license terms available at:
 * http://creativecommons.org/licenses/by/3.0/us/deed.en_US
 * 
 * It is the intent of the author(s) that you may use or
 * modify this software for any purpose (including your own
 * commercial gain) provided that this notice remains in its
 * entirety.
 * 
 * Created by Elliott Frisch - www.frischcode.com
 */
package com.frischcode.util;

/**
 * <b>Rationale:</b> Frequently you have something 
 * Comparable and you need a Comparator.
 * 
 * @author Elliott Frisch
 */
public class ComparableComparator<T extends Comparable<T>> 
    implements java.util.Comparator<T> {
  /**
   * @see java.util.Comparator#compare(java.lang.Object, 
   *     java.lang.Object)
   */
  @Override
  public int compare(T o1, T o2) {
    if (o1 != null) {
      return o1.compareTo(o2);
    } else if (o2 != null) {
      return -1;
    }
    return 0;
  }
}