野原新之楠 2019-04-06 15:53 采纳率: 80%
浏览 299
已采纳

Java 关于如何override hashcode的问题

3个练习里分别要定义3中ADT(abstract data type)
1. FList (定义一个list)
2. FSet (定义一个set)
3. FMap(定义一个map)

在改写hashcode时候遇到了困难。前两个练习没有做关于hashcode的说明
我直接 return FList.size() 和 FSet.size() ps:我知道这样不对。。。。。

第3个练习里有了规定 瞬间不懂了。。。

If m1 and m2 are values of the FMap ADT, and

    ! (m1.equals(m2))



then m1.hashCode() is unlikely to be equal to m2.hashCode().

Note: The word "unlikely" will be interpreted as follows. For every type K and V, if both m1 and m2 are selected at random from a set of FMap values such that for every non-negative integer n and int value h the probability of a randomly selected FMap m having

n == m.size() is

P(n) = 1/(2^(n+1))

and for each key k such that m.containsKey(k) the probability that

     h == k.hashCode() is at most 1/5

and for each value v such that v.equals(m.get(k)) the probability that

     h == v.hashCode() is at most 1/5

and the three probabilities above are independent

then the probability of m1.hashCode() == m2.hashCode() when m1 and m2 are not equal is less than 40%.

这里面是要求我设计hashcode m1和m2相等概率小于40%?

  • 写回答

1条回答 默认 最新

  • threenewbee 2019-04-06 16:30
    关注

    不是hashcode m1和m2相等概率小于40%,而是在 m1 m2 不相等的情况下,hashcode相等的概率小于40%(这个概率一般叫做hash碰撞率)

    如果m1和m2相等,则hashcode必须100%相等
    40%其实基本上你可以无视了,除非你根本没有任何算法,否则不会触及到这么高的。
    一个典型的做法,就是把lst的每个元素的hashcode相加,最后取一个余数,就可以满足题意了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用