<< Chapter < Page | Chapter >> Page > |
When comparing two objects, there are two ways to look at the comparison behavior, which creates a notion of ordering between the two objects:
These two different outlooks on binary object ordering will be explored below in terms of the two Java interfaces that are used to model them.
java.lang.Comparable
There are many computing tasks that require performing some sort of comparison between data objects. A few data types are endowed with a "natural" ordering of their values. The integers have a natural ordering "less or equal to", labeled "<=", defined as follows.
n<= m iff m = n + k, for some non-negative integer k( Note : a rigorous mathematical definition of the set of non-negative integers is beyond the scope of this lecture).
The above natural order of the integers is a concrete instance of an abstract concept called an order relation. An order relation on a set S is a boolean function R on S x S that is
To model order relations that are naturally endowed in certain types of data objects, Java provides an interface called
Comparable
, which has exactly one method called
int compareTo(Object rhs)
, defined abstractly as
x.compareTo(y)<0
means
x is "less than" y
,x.compareTo(y) == 0
means
x is "equal to" y
, andx.compareTo(y)>0
means
y is "less than" x
.For example, the
Integer
class implements the
Comparable
interface as follows. If
x
and
y
are
Integer
objects then,
x.compareTo(y)<0
means
x<y
,x.compareTo(y) == 0
means
x == y
, andx.compareTo(y)>0
means
y<x
.Common data types that have a natural ordering among their values, such as
Double
,
String
,
Character
, all implement
Comparable
.
java.util.Comparator
Most of the time, the ordering among the data objects is an extrinsic operation imposed on the object by the user of the objects. For example, the Pizza objects in
homework 2 have no concepts of comparing among themselves, however, the user can impose an ordering on them by comparing their price/area ratios or their profits. To model extrinsic ordering relation, Java provides an interface in the
java.util
package called
Comparator
, which has exactly two methods:
int compare(Object x, Object y)
, to model the ordering
compare(x, y)<0
means
x is "less than" y
,compare(x, y) == 0
means
x is "equal to" y
, andcompare(x, y)>0
means
yis "less than" x
, and
boolean equals(Object x)
, to model equality of
Comparators
. Unlike the
equals
method of most objects, equality of
Comparator
s also requires that their comparison behavior be identical.Notification Switch
Would you like to follow the 'Principles of object-oriented programming' conversation and receive update notifications?