1

I'd like to design a class that holds comparison results about to objects.

Given I have a class Thing and that Thing has a bunch of properties. Now I have an engine that compares Thing instances (held in a collection) to one another. Comparisons are actually Types deriving from a Comparison base class and can be fairly complex (e.g. ColorComparison). The actual result is not of importance, only that the comparison results in a match. So if comparing two Thing instances succeeds the comparison will be stored in a Match class, along with information about the applied comparison. So a Match class might have the properties

  • ThingA
  • ThingB
  • Comparison

I later need to store the Match class instances in a HashSet for fast lookup. What identifies a Match is the combination of ThingA and ThingB. In a perfect world the Match class could provide the same Hash for ThingA = x and ThingB = y vs. ThingA = y and ThingB = x. It might be later needed that not only one Comparison is stored within a Match but several different.

Some additional implementation notes:

  • Once a Match class has been instanciated, both ThingA and ThingB are immutable
  • The Things inside a Match cannot be manipulated (e.g. I cannot store the relationship information inside them)

My question is, how to I design the Match class in a way that when the HashSet is searched for the x and y combination of Things it also finds the y and x combination.

  • @DocBrown Thanks for pointing out what is unclear about my question. It's kind of tough because English is not my mother tongue. I updated the question and hope it's clearer now. – Mats Jun 4 at 20:28
  • 2
    In a perfect world the Match class could provide the same Hash for ThingA = x and ThingB = y vs. ThingA = y and ThingB = x - Isn't that your answer right there? Is there a reason you can't just define your equals and hash code that way? – casablanca Jun 5 at 2:28
4

You just define hash() and equals() for Match such that it is independent of the ordering of thingA and thingB.

This can be done like so (pseudo-python):

class Match:
    def hash(self, other):
        return self.thingA.hash() + self.thingB.hash() + self.comparison.hash()

    def equals(self, other):
        if self.comparison != other.comparison:
            return False
        if self.thingA == other.thingA and self.thingB == other.thingB:
            return True
        return self.thingA == other.thingB  and self.thingB == other.thingA
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.