Comparing Java objects with equals() and hashcode()

What is the contract between equals() and hashcode()? Learn how these methods work together when comparing Java objects.

1 2 Page 2
Page 2 of 2
  • Forgetting to override hashcode() along with the equals() method or vice versa.
  • Not overriding equals() and hashcode() when using hash collections like HashSet.
  • Returning a constant value in the hashcode() method instead of returning a unique code per object.
  • Using == and equals interchangeably. The == compares Object references, whereas equals() compares object values.

What to remember about equals() and hashcode()

  • It’s a good practice to always override equals() and hashcode() methods in your POJOs.
  • Use an effective algorithm to generate a unique hashcode.
  • When overriding the equals() method, always override the hashcode() method as well.
  • The equals() method should compare the whole state of objects: values from fields.
  • The hashcode() method could be the ID of a POJO.
  • When the result of comparing two object's hashcodes is false, the equals() method should also be false.
  • If equals() and hashcode() are not overridden when using hash collections, the collection will have duplicate elements.

Learn more about Java

This story, "Comparing Java objects with equals() and hashcode() " was originally published by JavaWorld.

Copyright © 2019 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2
InfoWorld Technology of the Year Awards 2023. Now open for entries!