Search code examples
javaequalshashcodecontract

Contract Checking in Java - In Built? E.g. Hashcode/Equals


Is there any in-built contract checking in Java e.g. for the contract between a hashcode and the equals function?

For this question, let's stick with the hashcode/equals contract as an example, but I'm interested in contract checking in general. I have read in multiple places that equals and hashcode must satisfy a "contract" in Java:

  • Equals must follow the three rules of an equivalence relation and also must be consistent on repeated calls
  • Equal objects implies equal hashcodes

I understand the conditions, and they make sense to me. However, I'm wondering, is this just a contract that's written down on paper- essentially a strong guideline for developers to not write buggy code- or is it something that will be caught by Java as either a compile time or run time exception?


Solution

  • It will not be enforced at compile time.

    Some classes may enforce the behaviour at runtime - for example you could write a method that checks that two objects that are equal have the same hashcode or send an exception.

    Also note that there are situations where you may want to deviate from the recommended contract on purpose.