String.GetHashCode () uniqueness and collisions

Given two different lines, is it always that s.GetHashCode() != s1.GetHashCode()?

In this case, the number of different integers is less than the number of different lines?

+5
source share
3 answers

No. As a simple thought experiment: how many lines there (hint: a lot more than 2 32 , and therefore, how many unique hash codes can be (hint: 2 32 . See the problem? )

Hash codes just have to be equal whenever it Equalsreturns that both objects are equal. In addition, if two hash codes are not equal, then the objects themselves cannot be equal. There are no additional requirements, but they must be well distributed so that the hash tables can work well. So basically this:

enter image description here

Note the omission of the corresponding options ⇐. This is not equivalence; these are just two meanings.

To quote the documentation :

The hash function must have the following properties:

  • If two objects are compared as equal, the GetHashCode method for each object must return the same value. However, if two objects are not compared as equal, the GetHashCode methods for two objects should not return different values.

  • GetHashCode -, , Equals . , - , .

  • - .

+12

@Joey, , , - .

2 ^ 32 -, .

(2 ^ 32 + 1).

, - , - ​​. , 64- - ( -, 32- -, , ), 100 , 1 -. , 1%.

+6

, Object.GetHashCode() - ( , Joey ), , CLR , .

, hashcode ( AppDomain) , douplicate ( ).

The issue is also discussed here: The default implementation for Object.GetHashCode ()

0
source

All Articles