Implementing equals and hashCode

Implementing these methods is fairly simple. As this is a very common task, the IDEs support the generation of these methods. These methods are tied together so much that the menu items in the IDEs are not separate; they offer you to generate these methods at once.

Asking the IDE to generate the equals method will result in something like the following code:

@Override 
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyObjectJava7 that = (MyObjectJava7) o;
return Objects.equals(field1, that.field1) &&
Objects.equals(field2, that.field2) &&
Objects.equals(field3, that.field3);
}

For this sample, we have three Object fields named field1, field2, and field3. The code with any other types and fields will look very similar.

First, the method checks for object identity. One Object always equals itself. If the reference passed as argument is null and not an object, or they are of different class, then this generated method will return false. In other cases, the static method of the class Objects (note the plural) will be used to compare each of the fields.

The utility class Objects was introduced in Java 7, hence the name of the sample class. The static methods, equals and hash, support the override of the Object equals and hashCode methods. The hashCode creation before Java 7 was fairly complex and required the implementation of modulo arithmetic with some magic numbers that is hard to explain just looking at the code without knowing the mathematics behind it.

This complexity is now hidden behind the following Objects.hash method.

@Override 
public int hashCode() {
return Objects.hash(field1, field2, field3);
}

The generated method simply calls the Objects.hash method passing the important fields as arguments.

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

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