ProgramixGenericLib v4.0.0

com.programix.collections
Class ComparableComparator

java.lang.Object
  extended by com.programix.collections.ComparableComparator
All Implemented Interfaces:
Comparator

public class ComparableComparator
extends Object
implements Comparator

This Comparator can be used to compare types that are Comparable when a Comparator is required. This effectively converts the natural ordering Comparable implementation on a class to be accessible via a Comparator.

There is no public constructor on this class as there is only need for one instance, use SINGLETON.

Both references are cast into Comparable to complete the comparison.

If there is a chance that any of the references involved in the comparisons might be null, you can protect yourself against NullPointerException's by using either the NullFirstComparator or NullLastComparator wrappers to first check for null's before proceeding to the regular comparison.

Author:
Paul Hyde
See Also:
ReverseComparator, NullFirstComparator, NullLastComparator

Field Summary
static ComparableComparator SINGLETON
          The single instance of this class.
 
Method Summary
 int compare(Object obj1, Object obj2)
          This implementation of the compare method on Comparator will quickly check if both references are the same using == (which evaluates to true if both references are pointing to the same object or both are null).
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface java.util.Comparator
equals
 

Field Detail

SINGLETON

public static final ComparableComparator SINGLETON
The single instance of this class. This instance may be safely used by multiple threads at the same time.

Method Detail

compare

public int compare(Object obj1,
                   Object obj2)
This implementation of the compare method on Comparator will quickly check if both references are the same using == (which evaluates to true if both references are pointing to the same object or both are null). If the references are the same, then this will quickly return 0.

If the are not the same, then the references are cast into Comparable to complete the comparison.

Specified by:
compare in interface Comparator
Throws:
NullPointerException - if the first reference is null, and the second reference is not null. To deal with this possibility, check out NullFirstComparator and NullLastComparator.

ProgramixGenericLib v4.0.0

Copyright © 2001-2007 Programix Incorporated. All rights reserved. ProgramixGenericLib is free and is OSI Certified Open Source Software under the BSD license.