// Constructs a hash table with specified capacity. public HashTable(int initialCapacity) { if (initialCapacity < 1) { throw new ArgumentOutOfRangeException("initialCapacity"); } _array = new HashTableArray <TKey, TValue>(initialCapacity); // When the count exceeds this value, the next Add will cause the array to grow. _maxItemsAtCurrentSize = (int)(initialCapacity * _fillFactor) + 1; }
public void Add(TKey key, TValue value) // O(1) on average. O(n+1) when array growth occrus. { // Adds layer of abstraction over HashTableArray class. // If we are at capacity, the array needs to grow. if (_count >= _maxItemsAtCurrentSize) { // Allocate a larger array HashTableArray <TKey, TValue> largerArray = new HashTableArray <TKey, TValue>(_array.Capacity * 2); // Re-add each item to the new array foreach (HashTableNodePair <TKey, TValue> node in _array.Items) { largerArray.Add(node.Key, node.Value); } // The larger array is now the hash table storage. _array = largerArray; // Update the new max items cached value. _maxItemsAtCurrentSize = (int)(_array.Capacity * _fillFactor + 1); } _array.Add(key, value); _count++; }