Java Reference
In-Depth Information
You can use a relational operator in this context because the compareTo method
returns an int . Notice that the specific value of -1 isn't used for compareTo
because you are only guaranteed to get a negative value for a less-than relationship.
Table 10.4 summarizes the standard way to compare objects that implement the
Comparable interface.
Implementing the Comparable Interface
Many of the standard Java classes, such as String , implement the Comparable inter-
face. You can have your own classes implement the interface as well. Implementing
the Comparable interface will open up a wealth of off-the-shelf programming solu-
tions that are included in the Java class libraries. For example, there are built-in methods
for sorting lists and for speeding up searches. Many of these features will be discussed
in the next chapter.
As a fairly simple example, let's explore a class that can be used to keep track of a
calendar date. The idea is to keep track of a particular month and day, but not the
year. For example, the United States celebrates its independence on July 4 each year.
Similarly, an organization might want a list of its employees' birthdays that doesn't
indicate how old they are.
Table 10.4
Comparing Values Summary
Relationship
Primitive data ( int , double , etc.)
Objects ( Integer , String , etc.)
less than
if (x < y) {
if (x.compareTo(y) < 0) {
...
...
}
}
less than or
if (x <= y) {
if (x.compareTo(y) <= 0) {
equal to
...
...
}
}
equal to
if (x == y) {
if (x.compareTo(y) == 0) {
...
...
}
}
not equal to
if (x != y) {
if (x.compareTo(y) != 0) {
...
...
}
}
greater than
if (x > y) {
if (x.compareTo(y) > 0) {
...
...
}
}
greater than or
if (x >= y) {
if (x.compareTo(y) >= 0) {
equal to
...
...
}
}
 
 
Search WWH ::




Custom Search