动态 GetHash 函数的类设计
我需要计算多种类型实例的内部哈希码(某些类型是相互派生的)。这里有两个方面是动态的,并且可以独立变化。只有请求哈希的客户端才知道要使用什么哈希算法以及要包含哪些属性。
- 实际使用的算法 因为哈希计算可以改变。
- 哈希计算应考虑每种类型的哪些成员可以更改。
您将如何围绕这些要求设计您的类型?
I have the requirement to calculate an internal hashcode of instances of several types (some types are derived from each other). Two aspects are dynamic here and can vary independently. Only the client that requests the hash knows what hash algorithm is to be used and what properties are to be included.
- The actual algorithm that is used
for the hash caluctation can change. - What members for each type should be take into account for the hash calculation can change.
How would you design your types around these requirement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,要求所有“可哈希”对象实现相同的接口,并使用一个方法:
getHash()
。其次,引入一个抽象工厂实例化哈希策略。
示例(Java 1.6):
将决策正确封装在对象内,以及策略和对象的有效解耦。
First, require all "hashable" objects to implement the same interface, with one method:
getHash()
.Second, introduce an Abstract Factory instantiating hash Strategies.
Example (Java 1.6):
Proper encapsulation of decision making inside your objects, and an effective decoupling of strategies and objects.
以下是 Eric Lippert 提供的 GetHashCode() 的一些指南。
http://ericlippert.com/2011/02/28/ guidelines-and-rules-for-gethashcode/
摘录:
规则:当对象包含在依赖于哈希码保持稳定的数据结构中时,GetHashCode 返回的整数绝不能改变。
尽管危险,但允许创建一个哈希码值可以像对象字段一样发生变化的对象。变异。如果您有这样一个对象并将其放入哈希表中,那么改变该对象的代码和维护哈希表的代码需要有一些商定的协议,以确保该对象在存在时不会发生改变。哈希表。该协议的外观取决于您。
简而言之,如果生成哈希码的算法可以更改,那么您需要确保当对象位于集合中时它不会更改。
Here are some guidelines for GetHashCode() from Eric Lippert.
http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/
An excerpt:
Rule: the integer returned by GetHashCode must never change while the object is contained in a data structure that depends on the hash code remaining stable
It is permissible, though dangerous, to make an object whose hash code value can mutate as the fields of the object mutate. If you have such an object and you put it in a hash table then the code which mutates the object and the code which maintains the hash table are required to have some agreed-upon protocol that ensures that the object is not mutated while it is in the hash table. What that protocol looks like is up to you.
In short, if the algorithm for generating the hash code can change, then you need to make sure that it doesn't change while the object is in your collection.