/// <summary> /// Sets the capacity of the dictionary a value that is at least as big /// as the given value. The real capacity may be different (usually bigger) /// because of the internal calculation done to have better hashing distribution. /// </summary> public bool SetCapacity(int value) { int count = _count; if (value < count) { throw new ArgumentOutOfRangeException("value", "Can't set a capacity that is not enough to hold all the actual items (Count=" + count + ", value=" + value + ")."); } int newLength = DictionaryHelper.AdaptLength(value); if (newLength == _indexes.Length) { return(false); } var newNodes = new _ExtendedDictionaryNode <TKey, TValue> [newLength]; var newIndexes = new int[newLength]; for (int i = 0; i < newLength; i++) { newIndexes[i] = -1; } var oldNodes = _nodes; var oldIndexes = _indexes; int newNodeIndex = -1; foreach (int firstNodeIndex in oldIndexes) { int oldNodeIndex = firstNodeIndex; while (oldNodeIndex != -1) { int hashCode = oldNodes[oldNodeIndex]._hashCode; int newBucketIndex = hashCode % newLength; newNodeIndex++; newNodes[newNodeIndex]._hashCode = hashCode; newNodes[newNodeIndex]._key = oldNodes[oldNodeIndex]._key; newNodes[newNodeIndex]._nextNodeIndex = newIndexes[newBucketIndex]; newNodes[newNodeIndex]._value = oldNodes[oldNodeIndex]._value; newIndexes[newBucketIndex] = newNodeIndex; oldNodeIndex = oldNodes[oldNodeIndex]._nextNodeIndex; } } _indexOfFirstFree = -1; _indexes = newIndexes; _nodes = newNodes; return(true); }
/// <summary> /// Creates a new dictionary with the given capacity and key comparer. /// </summary> /// <param name="capacity">The capacity to use.</param> /// <param name="comparer">The comparer to use for the keys. A value of null means the default one will be used.</param> public HashMap(int capacity, IEqualityComparer <TKey> comparer) { capacity = DictionaryHelper.AdaptLength(capacity); _indexes = new int[capacity]; _nodes = new _ExtendedDictionaryNode <TKey, TValue> [capacity]; if (comparer == null) { comparer = EqualityComparer <TKey> .Default; } _comparer = comparer; int length = _indexes.Length; for (int i = 0; i < length; i++) { _indexes[i] = -1; } }