Compares two objects specified in the arguments and returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

The arguments are compared according to the following rules:

  1. If some of the arguments is null, the one is considered greater which is not null. (If both arguments are null the function returns 0.)

  2. If both arguments are Strings they are compared as strings lexicographically.

  3. If both arguments are Numbers they are compared as numbers.

  4. If both arguments are Date they are compared using java.util.Date.compareTo() method.

  5. If both arguments are Arrays they are compared by the following Java code:
    
    Object[] a1 = (Object[]) o1;
    Object[] a2 = (Object[]) o2;
    
    int n = Math.min (a1.length, a2.length);
    for (int i = 0; i < n; i ++)
    {
      int result = compare(a1[i], a2[i]);
      if (result != 0)
        return result;
    }
    
    return (a1.length < a2.length) ? -1 :
            (a1.length > a2.length) ? 1 : 0;
    
    The compare() method used in this code does the same as the one being described here.

  6. If both arguments are Vectors they are compared by the following Java code:
    
    Vector v1 = (Vector) o1;
    Vector v2 = (Vector) o2;
    
    int n = Math.min (v1.size(), v2.size());
    for (int i = 0; i < n; i ++)
    {
      int result = compare(v1.get(i), v2.get(i));
      if (result != 0)
        return result;
    }
    
    return (v1.size() < v2.size()) ? -1 :
            (v1.size() > v2.size()) ? 1 : 0;
    
    The compare() method used in this code does the same as the one being described here.

  7. If both arguments are instances of java.lang.Comparable interface the function returns result of the call:
    ((Comparable) o1).compareTo (o2);

  8. At last, if nothing of the above is true, the function result is produced by the following:
    o1.toString().compareTo (o2.toString())

This function is related to other comparison functions:

min(), max(), minElement(), maxElement()