Search code examples
javaobjecthashequality

Finding same objects in Java


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?


Solution

  • Here's sample pair of hashCode\equals generated by IDE:

    class Sample  {
        final int area;
        final Set<Integer> someData;
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Sample sample = (Sample) o;
    
            if (area != sample.area) return false;
            if (!someData.equals(sample.someData)) return false;
    
            return true;
        }
    
        @Override
        public int hashCode() {
            int result = area;
            result = 31 * result + someData.hashCode();
            return result;
        }
    }
    

    This code assumes someData can't be null -- to simplify things. You can see that equality of types is checked at first, then area equality is checked and then equality of Set<Integer> is checked. Note that built-in equals of Set is used in this -- so you have re-usage of that method. This is idiomatic way to test compound types for equality.