Can Java's hashCode produce same value for different strings?

前端 未结 12 853
情歌与酒
情歌与酒 2020-11-28 08:58

Is it possible to have same hashcode for different strings using java\'s hashcode function?or if it is possible then what is the % of its possibility?

12条回答
  •  爱一瞬间的悲伤
    2020-11-28 09:53

    Yes(not just in Java, it applies to any language), it can produce the same hash-code for different strings. I am recalling a rule taught by my professor, it might be useful here -

    Two same strings/value must have the same hashcode, but the converse is not true.

    example in python

    >>> hash('same-string')
    -5833666992484370527
    >>> hash('same-string')
    -5833666992484370527
    

    There might be another string which can match the same hash-code, so we can't derive the key using hash-code.

    The reason for two different string to have the same hash-code is due to the collision.

提交回复
热议问题