Java Reference
In-Depth Information
Notice that the two
Product
objects are equal if they have the same
id
, and two equal
Product
objects generate the same
hashCode
.
compareTo
Consistent with
equals
If you write a class that implements
Comparable
, you introduce new business logic
for determining equality. The
compareTo
method returns
0
if two objects are equal,
while your
equals
method returns
true
if two objects are equal. A natural ordering
that uses
compareTo
is said to be
consistent with equals
if and only if
x.equals(y)
is
true
whenever
x.compareTo(y)
equals
0
. You are strongly encouraged to make your
Comparable
classes consistent with
equals
because not all collection classes behave
predictably if the
compareTo
and
equals
methods are not consistent. For example, the
following
Product
class defi nes a
compareTo
method that is consistent with
equals
:
public class Product implements Comparable<Product> {
int id;
public boolean equals(Object obj) {
if(!(obj instanceof Product)) {
return false;
}
Product other = (Product) obj;
return this.id == other.id;
}
public int compareTo(Product obj) {
return this.id - obj.id;
}
}
If two
Product
objects are equal, they have the same
id
. Therefore, the return value of
compareTo
is
0
when comparing two equal
Product
objects, so this
compareTo
method is
consistent with
equals
.
Now that we have discussed the various types of collections in the Collections
Framework, let's put this knowledge to use by instantiating and using the collection classes
in the next section. Because all of the collections classes use generics and the exam requires
knowledge of generics, the next section discusses both topics simultaneously.
Search WWH ::
Custom Search