Method hashCode

The hashCode method returns an int. The documentation says that any class redefining this method should provide the following implementation:

  • Consistently return the same value if the object was not modified
  • Result the same int value for two objects that are equal (the equals method returns true)

The documentation also mentions that this is not a requirement to result different int values for objects that are not equal, but it is desirable to support the performance of the hash implementing collections.

If you violate any of these rules in the implementation of equals and hashCode, then the JDK classes using them will fail. As you can be sure that HashSet, HashMap, and similar classes were fully debugged, seeing that you added an object to a set and then the set reporting that it is not there will be a bewildering experience. However, only until you find out that the two objects being equal and stored in the set have different hashCode values, HashSet and HashMap will look for the object only in the bucket that is indexed by the hashCode value.

It is also a common mistake to store an object in a HashSet or HashMap and then modify it. The object is in the collection but you cannot find it because the hashCode returns a different value. Objects stored in a collection should not be modified unless you know what you are doing.

Many times, objects contain fields that are not interesting from the equality point of view. The hashCode and equals methods should be idempotent to those fields and you can alter those fields even after storing the object in a HashSet or in HashMap.

As an example, you may administer triangles in objects maintaining the coordinates of the vertices and the color of the triangle. However, you do not care about the color for equality, only that the two triangles are at the exact same location in the space. In that case, the equals and hashCode method should not take the field color into account. This way, we can paint our triangles; they will still be found in HashSet or HashMap no matter what the color field is.

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

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