ProgramixGenericLib v5.0.1

com.programix.collections
Class ComparableComparator<T extends Comparable>

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

public class ComparableComparator<T extends Comparable>
extends Object
implements Comparator<T>

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.

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

Constructor Summary
ComparableComparator()
           
 
Method Summary
 int compare(T obj1, T 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
 

Constructor Detail

ComparableComparator

public ComparableComparator()
Method Detail

compare

public int compare(T obj1,
                   T 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<T extends Comparable>
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 v5.0.1

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