-1

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?

ilija
  • 543
  • 1
  • 11
  • 19

4 Answers4

1

You just need your object to implement the Comparable interface and code your logic in the compareTo method. Here's a good link to help you achieve that.

talnicolas
  • 13,885
  • 7
  • 36
  • 56
  • 3
    This needed only if you going to sort objects. If you just need to have dictionary of such objects, you need just proper `hashCode()` and `equals()` – Victor Sorokin Apr 03 '12 at 12:56
1

Just compare their area first in equals (after the == and type check of course), and return false if these differ. If the areas equal, go on and compare the sets.

For implementing equals (and hashCode) in general, here is a relevant thread and a good article (including several further references).

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Péter Török
  • 114,404
  • 31
  • 268
  • 329
1

A rule of thumb is that you should compare all relevant fields in your equals() implementation (fastest first, so compare your areas up front, then the integer sets) and use THE SAME fields in your hashCode(). If in doubt, use Eclipse's Source - Generate hashCode() and equals()... feature (and then fix the equals() code to compare the areas first.)

Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
1

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.

Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51