开发者

Is there a way of defining the size of the key value?

In C# is there a way of defining the key size when you instantiate a new hash table?

Hashtable myHash = new Hashtable();

I want to use a long value for the key size but I seem to be exceeding the available key size as I am getting nega开发者_如何学Gotive numbers. I am multiplying together some prime numbers, the largest returned value being 23*23*23*23*23*23*23*23*23 = 1801152661463.

Thanks.


First of all you should use HashSet<T> if you're using .net 3.5 or newer, and Dictionary<T,bool> if you're using .net 2. Generic collections offer better compiletime checks, less casts and less boxing.

The int overflow most likely happens before insertion into the Hashtable in your current code. So you're observed bug is most likely unrelated to Hashtable, but it's a bug in your arithmetic code. You probably need to cast something to long. But unless you post the relevant code, I can't tell you where exactly the overflow happens.


Both the .NET Hashtable and HashSet<T> classes call object.GetHashCode() to retrieve the hash. Since GetHashCode() returns an int, that is the size of the hash key that is used.

If you'd like to provide your own hash function, you can either override GetHashCode() in the type you'll be inserting, or define a custom IEqualityComparer<T> and pass it to the HashSet constructor. However, the IEqualityComparer<T>.GetHashCode() method also returns an integer key, so I'm not sure this will meet your needs.

If your application needs a hash key larger than an int, you may need to create your own HashSet data structure.


Since the System.Object method GetHashCode() returns an int, I would say that your choice of hash code algorithm is restricted to those returning a 32-bit value (whether you want to call it signed or unsigned doesn't make a differece: the hash value is just an arbitrary 32-bit value).

And HashTable doesn't care what your keys or values are: as far is it's concerned, they're both just objects. You might want to make sure that your're properly overriding and implementing GetHashCode() and Equals(). Might want to think about your implementation of IComparable as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜