Generating toString(), equals(), and hashCode()

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.

Getting ready

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.

How to do it...

With the project open:

  1. Right-click on the CreatingToStringEqualsHashCodeApp project and select New and Java Class....
  2. On the New Java Class window, type Book under Class Name.
  3. Under package, type myclasses.
  4. And click Finish.

In the class body, insert the following:

int isbn;
String name;
String author;
int price;

Let's first generate toString():

  1. Place the cursor before the closing bracket (}).
  2. Press Alt+Insert.
  3. Select toString().... With all the fields selected, press Generate.
  4. NetBeans will then implement toString and place it inside the body of Book.java.

Now, for equals() and hashCode():

  1. Once again, place the cursor before the closing bracket (}).
  2. Select equals() and hashCode()....
  3. Press Alt+Insert.
  4. Select isbn.
  5. Click Generate.

After pressing Generate, it is possible to see hashCode implemented.

How it works...

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.

There's more...

Want to know more about hashCode and equals?

hashCode() and equals() rules

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.155.130