Función FindEntry en Dictionary.cs
He estado mirando la implementación del diccionario en .NET, ya que quería entender qué hace que el diccionario ContainsKey y la búsqueda sean rápidas:http://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,15debc34d286fdb3
La función ContainsKey básicamente conduce a FindEntry que se enumera a continuación:
buckets es una matriz de enteros y las entradas son una matriz de objetos Entry, que son estructuras que contienen HashCode, TKey y TValue.
Así que entiendo que esta búsqueda es rápida, ya que es una búsqueda de matriz simple.
private int FindEntry(TKey key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
Sin embargo, estoy tratando de entender estas 2 líneas:
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
1) Si no entiendo correctamente, 0x7FFFFFFF está allí para garantizar que no obtengamos un valor negativo. Entonces, ¿qué regresa la primera línea? ¿Es un entero simple o un primo?
2) En la segunda línea, ¿por qué inicializamos i en buckets [hashCode% buckets.Length]?