Java Interview Question

Use this intermediate question and answer to prepare for your next Java interview.

Which methods need to be implemented in an object for it to be used as a Key in a HashMap or HashSet? Briefly explain their use. What are the requirements on these methods for the HashMap or HashSet to work correctly?

The two methods required for correctly using any type as a Key in a HashMap or HashSet are hashCode and equals.

  • When testing if a key exists or to get the value for a key, first it will check the hashCode to see if there is anything in the bucket.
  • Once the bucket is located, it will call the equals method to see if the two objects match.
  • The hashCode method must generate the same hashCode values when the objects are equal.
  • The equals method must compare all the required variables which need to be equal in order for two objects to be considered equal.

Looking for developers?

Want to learn more about Gigster? Enter your email and one of our project engineers will be in touch.