C#의 Hashtable 클래스에서 지정된 키에 대한 해시 코드를 얻으려면 GetHash() 메서드를 사용하면 됩니다. 이 메서드는 Hashtable이 내부적으로 키를 저장하고 검색할 때 사용하는 해시 코드를 반환합니다.
GetHash() 메서드란?
GetHash(Object key) 메서드는 전달된 키 객체에 대해 해당 Hashtable의 해시 코드 공급자(IHashCodeProvider)가 계산한 해시 코드를 int 형태로 반환합니다. 기본 해시 코드 공급자는 Object.GetHashCode()를 사용합니다.
예제 1: 문자열 키의 해시 코드 구하기
다음 예제에서는 문자열 키를 가진 Hashtable을 만들고, 키 "D"에 대한 해시 코드를 출력합니다.
using System;
using System.Collections;
public class HashCode : Hashtable {
public static void Main(string[] args) {
HashCode hash = new HashCode();
hash.Add("A", "Jacob");
hash.Add("B", "Mark");
hash.Add("C", "Tom");
hash.Add("D", "Nathan");
hash.Add("E", "Tim");
hash.Add("F", "John");
hash.Add("G", "Gary");
Console.WriteLine("키와 값 쌍 출력...");
foreach(DictionaryEntry entry in hash) {
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.Write("키 D의 해시 코드 = " + (hash.GetHash("D")));
}
}실행 결과
키와 값 쌍 출력... G and Gary A and Jacob B and Mark C and Tom D and Nathan E and Tim F and John 키 D의 해시 코드 = -842352676
Hashtable은 요소를 특정 순서로 정렬하지 않기 때문에, foreach 루프로 출력할 때 키-값 쌍의 순서는 추가한 순서와 다를 수 있습니다.
예제 2: 문자(char) 키의 해시 코드 구하기
이번에는 문자 타입의 키를 사용하는 예제입니다. 여러 개의 키에 대한 해시 코드를 한 번에 확인할 수 있습니다.
using System;
using System.Collections;
public class HashCode : Hashtable {
public static void Main(string[] args) {
HashCode hash = new HashCode();
hash.Add('1', "One");
hash.Add('2', "Two");
hash.Add('3', "Three");
hash.Add('4', "Four");
Console.WriteLine("키와 값 쌍 출력...");
foreach(DictionaryEntry entry in hash) {
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("키 1의 해시 코드 = " + (hash.GetHash('1')));
Console.WriteLine("키 2의 해시 코드 = " + (hash.GetHash('2')));
Console.WriteLine("키 3의 해시 코드 = " + (hash.GetHash('3')));
Console.WriteLine("키 4의 해시 코드 = " + (hash.GetHash('4')));
}
}실행 결과
키와 값 쌍 출력... 3 and Three 2 and Two 4 and Four 1 and One 키 1의 해시 코드 = 3211313 키 2의 해시 코드 = 3276850 키 3의 해시 코드 = 3342387 키 4의 해시 코드 = 3407924
정리
Hashtable에서 특정 키의 해시 코드가 필요할 때는 GetHash() 메서드를 호출하기만 하면 됩니다. 다만 참고할 점은, 일반적인 애플리케이션 코드에서는 보통 key.GetHashCode()를 직접 사용하는 것이 더 간단하며, GetHash()는 주로 Hashtable 자체의 내부 동작 방식(해시 코드 공급자 적용)을 그대로 따르고 싶을 때 유용하다는 점입니다.