Skip to content

Commit fd847ea

Browse files
committed
Fix bug with CopyTo method of ChainedHashTable
If a hashTable node contain a list with some values then the method CopyTo try to fill an array by the end from this node. But need check existing next element in the list in the hashTable node.
1 parent 1cc477e commit fd847ea

File tree

1 file changed

+9
-20
lines changed

1 file changed

+9
-20
lines changed

DataStructures/Dictionaries/ChainedHashTable.cs

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -442,7 +442,7 @@ public void Add(TKey key, TValue value)
442442
// Decrease the number of free slots.
443443
_freeSlotsCount--;
444444
}
445-
else if (_hashTableStore[hashcode] != null && _hashTableStore[hashcode].Count > 0)
445+
else if (_hashTableStore[hashcode].Count > 0)
446446
{
447447
if (_hashTableStore[hashcode].ContainsKey(key) == true)
448448
throw new ArgumentException("Key already exists in the hash table.");
@@ -582,7 +582,7 @@ public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
582582

583583
int i = arrayIndex;
584584
int hashTableIndex = 0;
585-
int countOfElements = (array.Length - arrayIndex);
585+
var currentChainNode = new DLinkedListNode<TKey, TValue>();
586586

587587
while (true)
588588
{
@@ -591,30 +591,19 @@ public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
591591
if (i >= array.Length)
592592
break;
593593

594-
if (_hashTableStore[hashTableIndex] != null && _hashTableStore[hashTableIndex].Count > 0)
594+
if (_hashTableStore[hashTableIndex] != null)
595595
{
596-
if (_hashTableStore[hashTableIndex].Count == 1)
596+
currentChainNode = _hashTableStore[hashTableIndex].Head;
597+
while (currentChainNode != null && i < array.Length)
597598
{
598-
pair = new KeyValuePair<TKey, TValue>(_hashTableStore[hashTableIndex].First.Key, _hashTableStore[hashTableIndex].First.Value);
599+
pair = new KeyValuePair<TKey, TValue>(currentChainNode.Key, currentChainNode.Value);
599600
array[i] = pair;
600601
i++;
601602
hashTableIndex++;
602-
}
603-
else
604-
{
605-
var headOfChain = _hashTableStore[hashTableIndex].Head;
606-
607-
while (i < array.Length)
608-
{
609-
pair = new KeyValuePair<TKey, TValue>(headOfChain.Key, headOfChain.Value);
610-
array[i] = pair;
611-
i++;
612-
hashTableIndex++;
613603

614-
headOfChain = headOfChain.Next;
615-
}
616-
}//end-if-else
617-
}//end-if
604+
currentChainNode = currentChainNode.Next;
605+
}
606+
}
618607
else
619608
{
620609
hashTableIndex++;

0 commit comments

Comments
 (0)