Class TotalOrder

Object
TotalOrder

public class TotalOrder extends Object

This class provides total ordering for objects of any type.

When comparing two objects, it is first determined if the objects are mutually comparable. The rules below specify which objects are comparable and how are they compared.

If two objects are not comparable, then their relative order is determined by comparing their classes. Among classes, numbers and ComparableTuple instances come first, then come String instances, then come all other classes, in order of their class names.

Rules for comparable objects:

  • Numbers of primitive-equivalent types (Long, Double, etc, but not BigDecimal) are compared as numbers.
  • Strings are compared according to parameters used to create an instance of TotalOrder. Strict comparison, case-insensitive comparison and collator-based comparison are available. See the factory methods.
  • Instances of ComparableTuple are compared according to the rules of ComparableTuple. Also, ComparableTuple and numbers (as in the first rule) are mutually comparable, as if the number was a first element of a tuple.
  • If none of the above apply, instances of the same class that implements Comparable are compared using the class' compareTo() method.
  • Two objects of the same class that is not Comparable are compared as their toString() values.

Notes:

  • String comparison rules (collator-based or case-insensitive comparison) apply only when comparing String objects. They do not apply when comparing ComparableTuple elements, when comparing toString() values, or when comparing anything inside some class' compareTo() method.
  • String and ComparableTuple are not mutually comparable (unlike numbers and ComparableTuple), because of the different rules for comparing strings.

Usage

To sort a set of values, one needs to create a image of that set using wrap(java.lang.Object) function, then sort that image using COMPARATOR. To link back to the original values or some other keys, use wrappers with payload - see wrap(Object, Object).

Although there is a convenience method compare(Object, Object) for single comparison, this class does not implement Comparator<Object>, to avoid performance pitfall when sorting non-prepared values.