Programming Languages

Java equals and hashCode: A Small Interview Exercise

SoftwareJobs.io editorial24 November 20262 min read

Two Java objects can describe the same business item without being the same object in memory. Before discussing equals and hashCode in a Malta backend interview, be clear about which kind of equality you mean.

Start with two customer objects

Imagine two separately created customer objects, both with the reference C100. The default Object.equals behaviour checks object identity. If your application wants equality based on a customer reference, that is a design choice you need to implement consistently. Decide which fields define the value before writing the methods.

Keep the contract consistent

Oracle’s Object documentation explains that equal objects must have the same hash code. Overriding equals therefore generally requires a matching hashCode implementation. Two different objects can still have the same hash code; a hash value is not a unique customer reference.

Write tests before a clever explanation

  • An object equals itself.
  • Two objects with the agreed same reference compare equal.
  • Changing a field that defines equality changes the expected comparison.
  • Comparison with null is false.
  • Objects that compare equal return the same hash code.

Ask one design question

Should the fields used for equality change after the object is created? Think about the effect before using that object as a key in a hash-based collection. For practice, keep the identifying value fixed and explain why you chose it. A small, understandable example is enough to show the difference between memorising method names and designing consistent behaviour.

Sources and further reading

Browse current technology jobs in Malta →

PUT YOUR IDEAS INTO ACTION

What’s your next move?

Explore software, cloud and data roles that fit your skills and ambitions.

Explore opportunities
KEEP EXPLORING

More ideas for your next chapter