Java Reference
In-Depth Information
} else {
return false;
}
}
As you can see, the overridden equals() method first checks to see whether the
object that is passed as an argument is referencing the same object as the one that it is
being compared against. If so, a true result is returned. If both objects are not referen-
cing the same object in memory, the equals() method checks to see whether the
fields are equal. In this case, any two Team objects that contain the same values within
the name and city fields would be considered equal. Once the equals() method has
been overridden, the comparison of the two objects can be performed, as demonstrated
in solution 2 to this recipe.
The hashCode() method returns an int value that must consistently return the
same integer. There are many ways in which to calculate the hashCode of an object.
Perform a web search on the topic and you will find various techniques. One of the
most basic ways to implement the hashCode() method is to concatenate all the ob-
ject's variables into string format and then return the resulting string's hashCode() .
It is a good idea to cache the value of the hashCode for later use because the initial
calculation may take some time. The hashCode() method in solution 2 demonstrates
this tactic.
Comparing Java objects can become confusing, considering that there are multiple
ways to do it. If the comparison that you want to perform is against the object identity,
use the comparison ( == ) operator. However, if you want to compare the values within
the objects, or the state of the objects, then the equals() method is the way to go.
5-12. Extending the Functionality of a
Class
Problem
One of your applications contains a class that you would like to use as a base for anoth-
er class. You want your new class to contain the same functionality of this base class,
but also include additional functionality.
Search WWH ::




Custom Search