Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

c# - Guid & GetHashCode uniqueness

Given the following key:

int key = Guid.NewGuid().GetHashCode();

Is this key unique as the uniqueness of Guid?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The pigeonhole principle says no. A GUID has 16 bytes of information - 128 bits. An int has 32 bits of information. (EDIT: To clarify due to comments, the .NET GUID will allow these 128 bits to be set arbitrarily as far as I'm aware; randomly generated GUIDs follow a stricter pattern so there aren't 2128 different values which would be randomly generated. Still more than 232 though.)

There are 2128 possible GUIDs, and 232 possible hash codes - so you can't possibly have a different hash code for each GUID.

There's more than that though - GetHashCode() is never meant to represent uniqueness. If it can, then that's great - but it doesn't have to, even when there are enough int values available to do so.

It would be entirely valid for int.GetHashCode() to return (say) the value divided by two... so -1, 0 and 1 would all get a hash code of 0; 3 and 4 would get a hash code of 2 etc. It wouldn't be good (and it would be slower than just returning the value) - but it would be a valid implementation. It would satisfy all the constraints of GetHashCode - namely that if you call it on two equal values, it will return the same hash code.

In fact, returning a constant for all values is a valid implementation - although a pretty useless one, in that it renders the normally-fast lookup of a hash table into an O(N) operation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...