Middle+
Ao rehashing, a hash permanece o mesmo ou é calculado um novo para a chave?
sobes.tech IA
Resposta da IA
Ao fazer rehashing em estruturas de dados, como tabelas de hash, um novo hash é calculado para cada chave. Isso ocorre porque o tamanho da tabela muda e, para distribuir corretamente os elementos nas novas cestas, é necessário recalcular o hash considerando o novo tamanho.
Ou seja, o hash antigo não é mantido, mas para cada chave, a função de hash é chamada novamente, e o resultado é usado para determinar a nova posição na tabela expandida.
Exemplo em Go:
// Ao aumentar o tamanho da tabela, rehash é chamado
func (ht *HashTable) rehash() {
oldBuckets := ht.buckets
ht.buckets = make([][]Entry, newSize)
for _, bucket := range oldBuckets {
for _, entry := range bucket {
newIndex := hash(entry.key) % newSize
ht.buckets[newIndex] = append(ht.buckets[newIndex], entry)
}
}
}
Assim, o hash para a chave é recalculado durante o rehashing.