IT박스

Hashtable의 제네릭 버전은 무엇입니까?

itboxs 2020. 11. 7. 09:07
반응형

Hashtable의 제네릭 버전은 무엇입니까?


.NET에서 제네릭의 기초를 배우고 있습니다. 그러나 Hashtable. 일반 해시 테이블 클래스를 만들기위한 몇 가지 샘플 C # 코드를 공유하세요.


Dictionary<TKey, TValue>

Dictionary는 HashTable을 100 % 대체하지 않습니다.

NULL을 처리하는 방식에 약간의 차이가 있습니다. 존재하지 않는 키를 참조하려고하면 사전에서 예외가 발생합니다. HashTable은 null을 반환합니다. 그 이유는 값이 null 일 수없는 값 유형일 수 있기 때문입니다 . Hashtable에서 값은 항상 Object 였으므로 최소한 null을 반환하는 것은 가능했습니다.


Hashtable 클래스의 제네릭 버전은 System.Collections.Generic.Dictionary 클래스입니다.

샘플 코드 :

Dictionary<int, string> numbers = new Dictionary<int, string>( );
   numbers.Add(1, "one");
   numbers.Add(2, "two");
   // Display all key/value pairs in the Dictionary.
   foreach (KeyValuePair<int, string> kvp in numbers)
   {
      Console.WriteLine("Key: " + kvp.Key + "\tValue: " + kvp.Value);
   }

Hashtable의 일반 버전은 Dictionary<TKey,TValue>클래스 ( link )입니다. 다음은 Hashtable을 사용하여 Dictionary와 가장 직접적으로 동등한 것으로 번역 된 일부 샘플 코드입니다 (간결성을 위해 인수 검사가 제거됨).

public HashTable Create(int[] keys, string[] values) { 
  HashTable table = new HashTable();
  for ( int i = 0; i < keys.Length; i++ ) {
    table[keys[i]] = values[i];
  }
  return table;
}

public Dictionary<object,object> Create(int[] keys, string[] values) {
  Dictionary<object,object> map = Dictionary<object,object>();
  for ( int i = 0; i < keys.Length; i++) {
    map[keys[i]] = values[i];
  }
  return map;
}

그것은 상당히 직접적인 번역입니다. 그러나 문제는 이것이 실제로 제네릭의 유형 안전 기능을 활용하지 않는다는 것입니다. 두 번째 함수는 다음과 같이 작성 될 수 있으며 훨씬 더 안전한 형식이며 권투 오버 헤드가 발생하지 않습니다.

public Dictionary<int,string> Create(int[] keys, string[] values) {
  Dictionary<int,string> map = Dictionary<int,string>();
  for ( int i = 0; i < keys.Length; i++) {
    map[keys[i]] = values[i];
  }
  return map;
}

더 좋습니다. 다음은 완전히 일반적인 버전입니다.

public Dictionary<TKey,TValue> Create<TKey,TValue>(TKey[] keys, TValue[] values) {
  Dictionary<TKey,TValue> map = Dictionary<TKey,TValue>();
  for ( int i = 0; i < keys.Length; i++) {
    map[keys[i]] = values[i];
  }
  return map;
}

그리고 훨씬 더 유연한 것 (이것을 놓쳤다는 Joel에게 감사드립니다)

public Dictionary<TKey,TValue> Create<TKey,TValue>(
    IEnumerable<TKey> keys, 
    IEnumerable<TValue> values) {

  Dictionary<TKey,TValue> map = Dictionary<TKey,TValue>();
  using ( IEnumerater<TKey> keyEnum = keys.GetEnumerator() ) 
  using ( IEnumerator<TValue> valueEnum = values.GetEnumerator()) {
    while (keyEnum.MoveNext() && valueEnum.MoveNext() ) { 
      map[keyEnum.Current] = valueEnum.Current;
    }
  }
  return map;
}

관심이있는 사람들을 위해 제네릭 Hashtable 래퍼 클래스를 만들었습니다.이 클래스는 형식 안전성을 강화하는 데 유용하고 제네릭 IDictionary, ICollection 및 IEnumerable 형식으로 전달할 수 있지만 제네릭이 아닌 Hashtable은 그렇지 않습니다. 아래는 구현입니다.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.Collections.Generic
{
    public class Hashtable<TKey, TValue> : IDictionary<TKey, TValue>
        , ICollection<KeyValuePair<TKey, TValue>>
        , IEnumerable<KeyValuePair<TKey, TValue>>
        , IDictionary
        , ICollection
        , IEnumerable
    {
        protected Hashtable _items;
        /// <summary>
        /// Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code provider, and comparer.
        /// </summary>
        public Hashtable()
        {
            _items = new Hashtable();
        }
        /// <summary>
        /// Initializes a new, empty instance of the Hashtable class using the specified initial capacity, and the default load factor, hash code provider, and comparer.
        /// </summary>
        /// <param name="capacity">The approximate number of elements that the Hashtable object can initially contain. </param>
        public Hashtable(int capacity)
        {
            _items = new Hashtable(capacity);
        }
        /// <summary>
        /// Actual underlying hashtable object that contains the elements.
        /// </summary>
        public Hashtable Items { get { return _items; } }

        /// <summary>
        /// Adds an element with the specified key and value into the Hashtable.
        /// </summary>
        /// <param name="key">Key of the new element to add.</param>
        /// <param name="value">Value of the new elment to add.</param>
        public void Add(TKey key, TValue value)
        {
            _items.Add(key, value);
        }
        /// <summary>
        /// Adds an element with the specified key and value into the Hashtable.
        /// </summary>
        /// <param name="item">Item containing the key and value to add.</param>
        public void Add(KeyValuePair<TKey, TValue> item)
        {
            _items.Add(item.Key, item.Value);
        }

        void IDictionary.Add(object key, object value)
        {
            this.Add((TKey)key, (TValue)value);
        }
        /// <summary>
        /// Add a list of key/value pairs to the hashtable.
        /// </summary>
        /// <param name="collection">List of key/value pairs to add to hashtable.</param>
        public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> collection)
        {
            foreach (var item in collection)
                _items.Add(item.Key, item.Value);
        }
        /// <summary>
        /// Determines whether the Hashtable contains a specific key.
        /// </summary>
        /// <param name="key">Key to locate.</param>
        /// <returns>True if key is found, otherwise false.</returns>
        public bool ContainsKey(TKey key)
        {
            return _items.ContainsKey(key);
        }
        /// <summary>
        /// Determines whether the Hashtable contains a specific key.
        /// </summary>
        /// <param name="item">Item containing the key to locate.</param>
        /// <returns>True if item.Key is found, otherwise false.</returns>
        public bool Contains(KeyValuePair<TKey, TValue> item)
        {
            return _items.ContainsKey(item.Key);
        }

        bool IDictionary.Contains(object key)
        {
            return this.ContainsKey((TKey)key);
        }
        /// <summary>
        /// Gets an ICollection containing the keys in the Hashtable.
        /// </summary>
        public ICollection<TKey> Keys
        {
            get { return _items.ToList<TKey>(); }
        }

        ICollection IDictionary.Keys
        {
            get { return this.Keys.ToList(); }
        }
        /// <summary>
        /// Gets the value associated with the specified key.
        /// </summary>
        /// <param name="key">The key of the value to get.</param>
        /// <param name="value">When this method returns, contains the value associated with the specified key,
        /// if the key is found; otherwise, the default value for the type of the value parameter. This parameter 
        /// is passed uninitialized.</param>
        /// <returns>true if the hashtable contains an element with the specified key, otherwise false.</returns>
        public bool TryGetValue(TKey key, out TValue value)
        {
            value = (TValue)_items[key];
            return (value != null);
        }
        /// <summary>
        /// Gets an ICollection containing the values in the Hashtable.
        /// </summary>
        public ICollection<TValue> Values
        {
            get { return _items.Values.ToList<TValue>(); }
        }

        ICollection IDictionary.Values
        {
            get { return this.Values.ToList(); }
        }
        /// <summary>
        /// Gets or sets the value associated with the specified key.
        /// </summary>
        /// <param name="key">The key whose value to get or set. </param>
        /// <returns>The value associated with the specified key. If the specified key is not found, 
        /// attempting to get it returns null, and attempting to set it creates a new element using the specified key.</returns>
        public TValue this[TKey key]
        {
            get
            {
                return (TValue)_items[key];
            }
            set
            {
                _items[key] = value;
            }
        }
        /// <summary>
        /// Removes all elements from the Hashtable.
        /// </summary>
        public void Clear()
        {
            _items.Clear();
        }
        /// <summary>
        /// Copies all key/value pairs in the hashtable to the specified array.
        /// </summary>
        /// <param name="array">Object array to store objects of type "KeyValuePair&lt;TKey, TValue&gt;"</param>
        /// <param name="arrayIndex">Starting index to store objects into array.</param>
        public void CopyTo(Array array, int arrayIndex)
        {
            _items.CopyTo(array, arrayIndex);
        }
        /// <summary>
        /// Copies all key/value pairs in the hashtable to the specified array.
        /// </summary>
        /// <param name="array">Object array to store objects of type "KeyValuePair&lt;TKey, TValue&gt;"</param>
        /// <param name="arrayIndex">Starting index to store objects into array.</param>
        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            _items.CopyTo(array, arrayIndex);
        }
        /// <summary>
        /// Gets the number of key/value pairs contained in the Hashtable.
        /// </summary>
        public int Count
        {
            get { return _items.Count; }
        }
        /// <summary>
        /// Gets a value indicating whether the Hashtable has a fixed size.
        /// </summary>
        public bool IsFixedSize
        {
            get { return _items.IsFixedSize; }
        }
        /// <summary>
        /// Gets a value indicating whether the Hashtable is read-only.
        /// </summary>
        public bool IsReadOnly
        {
            get { return _items.IsReadOnly; }
        }
        /// <summary>
        /// Gets a value indicating whether access to the Hashtable is synchronized (thread safe).
        /// </summary>
        public bool IsSynchronized
        {
            get { return _items.IsSynchronized; }
        }
        /// <summary>
        /// Gets an object that can be used to synchronize access to the Hashtable.
        /// </summary>
        public object SyncRoot
        {
            get { return _items.SyncRoot; }
        }
        /// <summary>
        /// Removes the element with the specified key from the Hashtable.
        /// </summary>
        /// <param name="key">Key of the element to remove.</param>
        public void Remove(TKey key)
        {
            _items.Remove(key);
        }
        /// <summary>
        /// Removes the element with the specified key from the Hashtable.
        /// </summary>
        /// <param name="item">Item containing the key of the element to remove.</param>
        public void Remove(KeyValuePair<TKey, TValue> item)
        {
            this.Remove(item.Key);
        }

        bool IDictionary<TKey, TValue>.Remove(TKey key)
        {
            var numValues = _items.Count;
            _items.Remove(key);
            return numValues > _items.Count;
        }

        bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
        {
            var numValues = _items.Count;
            _items.Remove(item.Key);
            return numValues > _items.Count;
        }

        void IDictionary.Remove(object key)
        {
            _items.Remove(key);
        }
        /// <summary>
        /// Returns an enumerator that iterates through the hashtable.
        /// </summary>
        /// <returns>An enumerator for a list of key/value pairs.</returns>
        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            foreach (DictionaryEntry? item in _items)
                yield return new KeyValuePair<TKey, TValue>((TKey)item.Value.Key, (TValue)item.Value.Value);
        }
        /// <summary>
        /// Returns an enumerator that iterates through the hashtable.
        /// </summary>
        /// <returns>An enumerator for a list of key/value pairs as generic objects.</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        IDictionaryEnumerator IDictionary.GetEnumerator()
        {
            // Very old enumerator that no one uses anymore, not supported.
            throw new NotImplementedException(); 
        }

        object IDictionary.this[object key]
        {
            get
            {
                return _items[(TKey)key];
            }
            set
            {
                _items[(TKey)key] = value;
            }
        }
    }
}

이 Hashtable 대 Dictionary에 대한 몇 가지 테스트를 수행했으며 Hashtable이 더 적은 메모리를 사용하는 것처럼 보인다는 점을 제외하면 두 가지가 문자열 키와 문자열 값 쌍과 함께 사용될 때 거의 동일한 성능을 발휘한다는 것을 발견했습니다. 내 테스트 결과는 다음과 같습니다.

TestInitialize Dictionary_50K_Hashtable
Number objects 50000, memory usage 905164
Insert, 22 milliseconds.
A search not found, 0 milliseconds.
Search found, 0 milliseconds.
Remove, 0 milliseconds.
Search found or not found, 0 milliseconds.
TestCleanup Dictionary_50K_Hashtable

TestInitialize Dictionary_50K_Dictionary
Number objects 50000, memory usage 1508316
Insert, 16 milliseconds.
A search not found, 0 milliseconds.
Search found, 0 milliseconds.
Remove, 0 milliseconds.
Search found or not found, 0 milliseconds.
TestCleanup Dictionary_50K_Dictionary

의 일반 버전은 System.Collection.Hashtable입니다 System.Collections.Generic.Dictionary<TKey, TValue>.

참고 URL : https://stackoverflow.com/questions/772831/what-is-the-generic-version-of-a-hashtable

반응형