touque.ca > Education Commons > Java > Resources

compareTo method

a.compareTo(b) returns

Implementation

Programmers are responsible for implementing the compareTo method whenever they create a class whose objects might need to be ordered. The class of the method’s formal parameter should be the same as that of the class being created.

/**
 * Compares this object with the specified object for order. Returns a negative
 * integer, zero, or a positive integer as this object is less than, equal to, or
 * greater than the specified object.
 *
 * @param otherObject the object whose order is compared to this object’s
 * @return a negative integer, zero, or a positive integer as this object is less
 * than, equal to, or greater than the specified object
 */
public int compareTo(Object otherObject)
{
   // actual comparison goes here
} // end of method compareTo(Object otherObject)

The class being created should implement the Comparable interface; the sole method of that interface is compareTo.

touque.ca > Education Commons > Java > Resources

[This page last updated 2020-12-23 at 12h13 Toronto local time.]