关于扑克游戏中 Card 对象的哈希码的建议?
如何为由枚举花色和枚举等级组成的卡片对象计算哈希码?
How is the hashcode computed for a card object which consists of enum suit and enum rank ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 Eclipse,它可以为您生成一个“足够好”的
hashCode()
实现:我只能想象 NetBeans、IntelliJ IDEA 等也可以做到这一点。
也就是说,由于域很小,这个实现同样可以很好地工作(我认为......):
这假设
Rank
序数包含0-12
并且>Suit
序数包括0-3
。请注意,大部分丑陋的情况都来自空检查。如果这些值永远不能为空,那么:If you're using Eclipse, it can generate a "good enough"
hashCode()
implementation for you:I can only imagine that NetBeans, IntelliJ IDEA, etc., can do this as well.
That said, since the domain is small, this implementation will work equally well (I think...):
This assumes that
Rank
ordinals are0-12
inclusive andSuit
ordinals are0-3
inclusive. Note that most of the ugliness there comes from the null checks. If the values can never be null, then:由于值空间如此之小(是 13 乘以 4 吗?),为任何两张卡分配相同的哈希码是没有意义的。所以这完全取决于你,但类似这样的事情
应该没问题。
一般来说,如果确实存在大量可能的值(例如每个可能的
String
值或每个可能的数字列表List
),那么定义哈希码是有意义的将它们限制为(投影到)有限的哈希码值空间。如果我们讨论的是java.lang.Object
API 定义的hashCode()
,那么“哈希码值的有限空间”必须适合int类型(整数)。
With so little value space (is it 13 times 4?) it makes no sense to assign any two cards the same hash-code. So it's completely up to you, but something like:
should be OK.
Generally it makes sense to define a hashcode if there are really huge numbers of possible values (like every possible
String
value or every possible list of numbersList<Number>
) and to have them limited to (projected into) a limited space of hashcode values. If we are talking abouthashCode()
as defined byjava.lang.Object
API then the 'limited space of hashcode values' has to fit intoint
type (integers).卡域 ( 52 ) 的空间足够小,足以容纳其自身的
枚举
。这也将为您提供一个用于识别的自然主键,因为 hashCode 也应该是对象内部状态的唯一标识符。下面是一些伪 Java 代码,可以让您了解一下:
The space of the cards domain ( 52 ) is small enough to fit into an
enum
it self. And that would give you a natural primary key for identification as well, sincehashCode
should be a unique identifier for the internal state of the object as well.Here is some pseudo Java code to give you an idea: