我想设计一个类来保存与对象的比较结果。
考虑到我有一个类Thing,并且Thing有很多属性。现在,我有了一个引擎,它可以将Thing实例(保存在集合中)进行相互比较。比较实际上是从Comparison基类派生的类型,并且可能相当复杂(例如,ColorComparison)。实际结果并不重要,只是比较的结果是匹配的。因此,如果比较两个Thing实例成功,则比较将存储在Match类中,以及有关应用比较的信息。因此,Match类可能具有以下属性
之后,为了快速查找,我需要将Match类实例存储在HashSet中。识别Match的是ThingA和ThingB的组合。在一个完美的世界中,Match类可以为ThingA = x和ThingB =y和ThingA =y和ThingB =x提供相同的哈希。
另有一些执行说明:
Match类,ThingA和ThingB都是不可变的。Match内部的东西不能被操纵(例如,我不能在它们中存储关系信息)我的问题是,如何设计Match类,使HashSet在搜索Things的x和y组合时,也能找到y和x组合。
发布于 2020-06-05 04:44:05
您只需为hash()和equals()定义Match,使其独立于thingA和thingB的顺序。
可以这样做(伪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.thingAhttps://softwareengineering.stackexchange.com/questions/411067
复制相似问题