I produce a bunch of objects in Java. Each object has attribute area and a set of integers. I want to store those objects for example in a map(keys should be integers in a growing order). Two objects are the same if their area is equal and their sets are the same.
If two objects don’t have the same area then there is no need for me to check whether their sets are the same.
What is the best practice for implementing this in Java? How should I compose hash and equal functions?
Here’s sample pair of
hashCode\equalsgenerated by IDE:This code assumes
someDatacan’t be null — to simplify things. You can see that equality of types is checked at first, thenareaequality is checked and then equality ofSet<Integer>is checked. Note that built-inequalsofSetis used in this — so you have re-usage of that method. This is idiomatic way to test compound types for equality.