Java Reference
In-Depth Information
The == operator tests two references to see if they refer to the same object. If you
want to test whether two distinct objects are equal to one another, you must use the
equals() method instead. Any class can define its own notion of equality by over‐
riding equals() . The Object.equals() method simply uses the == operator: this
default method considers two objects equal only if they are actually the very same
The equals() method in Example 5-1 considers two distinct Circle objects to be
equal if their fields are all equal. Note that it first does a quick identity test with == as
an optimization and then checks the type of the other object with instanceof : a
Circle can be equal only to another Circle , and it is not acceptable for an
equals() method to throw a ClassCastException . Note that the instanceof test
also rules out null arguments: instanceof always evaluates to false if its left-hand
operand is null .
Whenever you override equals() , you must also override hashCode() . This method
returns an integer for use by hash table data structures. It is critical that two objects
have the same hash code if they are equal according to the equals() method. It is
important (for efficient operation of hash tables) but not required that unequal
objects have unequal hash codes, or at least that unequal objects are unlikely to
share a hash code. This second criterion can lead to hashCode() methods that
involve mildly tricky arithmetic or bit manipulation.
O n
The Object.hashCode() method works with the Object.equals() method and
returns a hash code based on object identity rather than object equality. (If you ever
need an identity-based hash code, you can access the functionality of Object.hash
Code() through the static method System.identityHashCode() .)
When you override equals() , you must always override hash
Code() to guarantee that equal objects have equal hash codes.
Failing to do this can cause subtle bugs in your programs.
Because the equals() method in Example 5-1 bases object equality on the values of
the three fields, the hashCode() method computes its hash code based on these
three fields as well. It is clear from the code that if two Circle objects have the same
field values, they will have the same hash code.
Note that the hashCode() method in Example 5-1 does not simply add the three
fields and return their sum. Such an implementation would be legal but not efficient
because two circles with the same radius but whose x and y coordinates were
reversed would then have the same hash code. The repeated multiplication and
Search WWH ::

Custom Search