하랑이 코딩

컴퓨터공학/자료구조

선형 자료구조 - 해시테이블과 딕셔너리 c#

하랑이~! 2024. 6. 5. 14:43

해시테이블(HashTable)과 딕셔너리(Dictionary)


해시테이블(HashTable)

  • 해시 테이블키-값 쌍을 저장하는 데이터 구조로, 각 키를 해시 함수에 의해 계산된 해시 값을 기반으로 인덱싱하여 빠르게 데이터에 접근할 수 있습니다. 이는 평균적으로 O(1)의 시간 복잡도로 삽입, 삭제, 검색을 수행할 수 있게 합니다.

 

 

딕셔너리(Dictionary)

  • 딕셔너리키-값 쌍을 저장하고 관리하는 데이터 구조로, 각 키는 고유하며 해시 함수를 통해 빠르게 접근할 수 있습니다. 키를 통해 값에 직접 접근할 수 있어 삽입, 삭제, 검색 연산이 평균적으로 O(1)의 시간 복잡도로 효율적으로 수행됩니다.

 

 

해시테이블(HashTable)과 딕셔너리(Dictionary) 차이는?

  • 해시테이블: 비제네릭 컬렉션으로, 키와 값 모두 object 타입으로 저장되기 때문에 형식 안전성이 없습니다. 사용 시 명시적인 캐스팅이 필요합니다.
  • 딕셔너리 : 제네릭 컬렉션으로, 키와 값의 타입을 명시할 수 있어 형식 안전성을 제공합니다. 컴파일 타임에 타입 검사가 이루어지며, 명시적인 캐스팅이 필요하지 않습니다.

 

 

해시테이블(HashTable) 사용법


using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        // Hashtable 생성
        Hashtable hashtable = new Hashtable();

        // 키-값 쌍 추가
        hashtable.Add(1, "One");
        hashtable.Add(2, "Two");
        hashtable.Add(3, "Three");

        // 키를 사용하여 값 검색
        Console.WriteLine("Key 1: " + hashtable[1]); // 출력: One
        Console.WriteLine("Key 2: " + hashtable[2]); // 출력: Two
        Console.WriteLine("Key 3: " + hashtable[3]); // 출력: Three

        // 모든 키-값 쌍 반복
        Console.WriteLine("\nAll key-value pairs:");
        foreach (DictionaryEntry entry in hashtable)
        {
            Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
        }

        // 값 업데이트
        hashtable[1] = "Uno";
        Console.WriteLine("\nUpdated Key 1: " + hashtable[1]); // 출력: Uno

        // 값 제거
        hashtable.Remove(2);
        Console.WriteLine("\nAfter removing Key 2:");

        // 모든 키-값 쌍 반복 (갱신된 상태)
        foreach (DictionaryEntry entry in hashtable)
        {
            Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
        }
    }
}

 

 

 

딕셔너리(Dictionary)  사용법


using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Dictionary 생성
        Dictionary<int, string> dictionary = new Dictionary<int, string>();

        // 키-값 쌍 추가
        dictionary.Add(1, "One");
        dictionary.Add(2, "Two");
        dictionary.Add(3, "Three");

        // 키를 사용하여 값 검색
        Console.WriteLine("Key 1: " + dictionary[1]); // 출력: One
        Console.WriteLine("Key 2: " + dictionary[2]); // 출력: Two
        Console.WriteLine("Key 3: " + dictionary[3]); // 출력: Three

        // 모든 키-값 쌍 반복
        Console.WriteLine("\nAll key-value pairs:");
        foreach (var entry in dictionary)
        {
            Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
        }

        // 값 업데이트
        dictionary[1] = "Uno";
        Console.WriteLine("\nUpdated Key 1: " + dictionary[1]); // 출력: Uno

        // 값 제거
        dictionary.Remove(2);
        Console.WriteLine("\nAfter removing Key 2:");

        // 모든 키-값 쌍 반복 (갱신된 상태)
        foreach (var entry in dictionary)
        {
            Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
        }

        // 값 존재 여부 확인
        if (dictionary.ContainsKey(3))
        {
            Console.WriteLine("\nDictionary contains key 3");
        }

        if (dictionary.ContainsValue("Uno"))
        {
            Console.WriteLine("Dictionary contains value 'Uno'");
        }
    }
}

 

 

728x90