To generate toString(), equals()
, and hashCode()
, the process is almost the same as with the constructor. However, it is important to know when to implement those methods and when not to. For example, if overriden, equals and hashCode must be implemented using the same set of fields in the code. The equals method should be used when equality is required, where it would be necessary to compare different instances of the class. The basic implementation checks for identity, the same as using ==. The hashCode method exists for two reasons: one being efficiency, so objects can be used with collections that require a hash, such as HashSet and HashMap, and the other being conformity with equals. So, when an object is equal to the other, hashCodes of those two objects must also be identical.
Check the recipe Creating a Java Project using Wizard.
Feel free to modify the default settings, but if you wish to follow exactly what we are presenting here, just modify the Project Name to CreatingToStringEqualsHashCodeApp and uncheck create main class.
With the project open:
In the class body, insert the following:
int isbn; String name; String author; int price;
Let's first generate toString():
toString
and place it inside the body of Book.java
.Now, for equals()
and hashCode():
After pressing Generate, it is possible to see hashCode implemented.
Since toString()
is a method which usually requires all the information from the implementing object, we added all the present fields to the implementation when we generated it.
The case is a bit different with ISBN, since it is already a unique number, and other fields like name or author do not satisfy the uniqueness condition, so it was the only one selected.
Want to know more about hashCode and equals?
There are few rules related to the use of hashCode and equals that are worth checking but are beyond the scope of this recipe:
http://www.ibm.com/developerworks/java/library/j-jtp05273.html
18.216.155.130