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

前端 未结 12 879
情歌与酒
情歌与酒 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:36

    Yes, it is entirely possible. The probability of a string (or some other object type -- just assuming you'll be using strings in this example) having the same hashcode as some other string in a collection, depends on the size of that collection (assuming that all strings in that collection are unique). The probabilities are distributed as follows:

    • With a set of size ~9,000, you'll have a 1% chance of two strings colliding with a hash in the set
    • With a set of size ~30,000, you'll have a 10% chance of two strings colliding with a hash in the set
    • With a set of size ~77,000, you'll have a 50% chance of two strings colliding with a hash in the set

    The assumptions made, are:

    • The hashCode function has no bias
    • Each string in the aforementioned set is unique

    This site explains it clearly: http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/ (Look at "the second thing you should know")

提交回复
热议问题