사전과 해시 테이블의 차이점
중복 가능성 :
C #에서 사전이 해시 테이블보다 선호되는 이유는 무엇입니까?
Dictionary와 Hashtable의 차이점은 무엇입니까? 어떤 것을 사용할지 결정하는 방법은 무엇입니까?
간단히 말해서 다음을
Dictionary<TKey,TValue>
허용하는 일반 유형입니다.
- 정적 타이핑 (및 컴파일 타임 검증)
- 권투없이 사용
.NET 2.0 이상인 경우
선호
해야 합니다
Dictionary<TKey,TValue>
(및 기타 일반 컬렉션).미묘하지만 중요한 차이점은
Hashtable
단일 작성기 스레드로 다중 판독기 스레드 를 지원하는 반면
Dictionary
스레드 안전성은 제공하지 않는다는 것입니다. 일반 사전과 함께 스레드 안전성이 필요한 경우 자체 동기화를 구현하거나 .NET 4.0에서
ConcurrentDictionary<TKey, TValue>
.
해시 테이블과 사전의 차이점을 설명하는 예를 들어 보겠습니다.다음은 해시 테이블을 구현하는 방법입니다.
public void MethodHashTable()
{
Hashtable objHashTable = new Hashtable();
objHashTable.Add(1, 100); // int
objHashTable.Add(2.99, 200); // float
objHashTable.Add('A', 300); // char
objHashTable.Add("4", 400); // string
lblDisplay1.Text = objHashTable[1].ToString();
lblDisplay2.Text = objHashTable[2.99].ToString();
lblDisplay3.Text = objHashTable['A'].ToString();
lblDisplay4.Text = objHashTable["4"].ToString();
// ----------- Not Possible for HashTable ----------
//foreach (KeyValuePair<string, int> pair in objHashTable)
//{
// lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
//}
}
다음은 사전 용입니다.
public void MethodDictionary()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
//dictionary.Add(1, -2); // Compilation Error
foreach (KeyValuePair<string, int> pair in dictionary)
{
lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
}
}
HashTable과 Dictionary 사이에 또 하나의 중요한 차이점이 있습니다. 인덱서를 사용하여 HashTable에서 값을 가져 오는 경우 HashTable은 존재하지 않는 항목에 대해 null을 성공적으로 반환하는 반면, 사전에없는 인덱서를 사용하여 항목에 액세스하려고하면 사전에서 오류가 발생합니다.
딕셔너리가 입력되고 (값 유형에는 권투가 필요하지 않음) Hashtable은 없습니다 (값 유형에는 권투가 필요함). Hashtable은 값이 객체라는 것을 항상 알고 있기 때문에 사전 IMHO보다 값을 얻는 더 좋은 방법을 가지고 있습니다. .NET 3.5를 사용하는 경우에도 유사한 동작을 얻기 위해 사전에 대한 확장 메서드를 작성하는 것은 쉽습니다.
If you need multiple values per key, check out my sourcecode of MultiValueDictionary here: multimap in .NET
Want to add a difference:
Trying to acess a inexistent key gives runtime error in Dictionary but no problem in hashtable as it returns null instead of error.
e.g.
//No strict type declaration
Hashtable hash = new Hashtable();
hash.Add(1, "One");
hash.Add(2, "Two");
hash.Add(3, "Three");
hash.Add(4, "Four");
hash.Add(5, "Five");
hash.Add(6, "Six");
hash.Add(7, "Seven");
hash.Add(8, "Eight");
hash.Add(9, "Nine");
hash.Add("Ten", 10);// No error as no strict type
for(int i=0;i<=hash.Count;i++)//=>No error for index 0
{
//Can be accessed through indexers
Console.WriteLine(hash[i]);
}
Console.WriteLine(hash["Ten"]);//=> No error in Has Table
here no error for key 0 & also for key "ten"(note: t is small)
//Strict type declaration
Dictionary<int,string> dictionary= new Dictionary<int, string>();
dictionary.Add(1, "One");
dictionary.Add(2, "Two");
dictionary.Add(3, "Three");
dictionary.Add(4, "Four");
dictionary.Add(5, "Five");
dictionary.Add(6, "Six");
dictionary.Add(7, "Seven");
dictionary.Add(8, "Eight");
dictionary.Add(9, "Nine");
//dictionary.Add("Ten", 10);// error as only key, value pair of type int, string can be added
//for i=0, key doesn't exist error
for (int i = 1; i <= dictionary.Count; i++)
{
//Can be accessed through indexers
Console.WriteLine(dictionary[i]);
}
//Error : The given key was not present in the dictionary.
//Console.WriteLine(dictionary[10]);
here error for key 0 & also for key 10 as both are inexistent in dictionary, runtime error, while try to acess.
The Hashtable class is a specific type of dictionary class that uses an integer value (called a hash) to aid in the storage of its keys. The Hashtable class uses the hash to speed up the searching for a specific key in the collection. Every object in .NET derives from the Object class. This class supports the GetHash method, which returns an integer that uniquely identifies the object. The Hashtable class is a very efficient collection in general. The only issue with the Hashtable class is that it requires a bit of overhead, and for small collections (fewer than ten elements) the overhead can impede performance.
There is Some special difference between two which must be considered:
HashTable: is non-generic collection ,the biggest overhead of this collection is that it does boxing automatically for your values and in order to get your original value you need to perform unboxing , these to decrease your application performance as penalty.
Dictionary: This is generic type of collection where no implicit boxing, so no need to unboxing you will always get your original values which you were stored so it will improve your application performance.
the Second Considerable difference is:
if your were trying to access a value on from hash table on the basis of key that does not exist it will return null.But in the case of Dictionary it will give you KeyNotFoundException.
ILookup Interface is used in .net 3.5 with linq.
The HashTable is the base class that is weakly type; the DictionaryBase abstract class is stronly typed and uses internally a HashTable.
I found a a strange thing about Dictionary, when we add the multiple entries in Dictionary, the order in which the entries are added is maintained. Thus if I apply a foreach on the Dictionary, I will get the records in the same order I have inserted them.
Whereas, this is not true with normal HashTable, as when I add same records in Hashtable the order is not maintained. As far as my knowledge goes, Dictionary is based on Hashtable, if this is true, why my Dictionary maintains the order but HashTable does not?
As to why they behave differently, it's because Generic Dictionary implements a hashtable, but is not based on System.Collections.Hashtable. The Generic Dictionary implementation is based on allocating key-value-pairs from a list. These are then indexed with the hashtable buckets for random access, but when it returns an enumerator, it just walks the list in sequential order - which will be the order of insertion as long as entries are not re-used.
shiv govind Birlasoft.:)
참고URL : https://stackoverflow.com/questions/876656/difference-between-dictionary-and-hashtable
'Programming' 카테고리의 다른 글
Java에서 현재 날짜를 문자열로 변환하는 방법은 무엇입니까? (0) | 2020.08.08 |
---|---|
선언되지 않은 식별자 'kUTTypeMovie'사용 (0) | 2020.08.08 |
정의되지 않은 매크로 : AC_MSG_ERROR (0) | 2020.08.08 |
PreferenceScreen에 버튼을 추가하는 방법 (0) | 2020.08.08 |
Spring-Data-JPA 주석에 대한 setMaxResults? (0) | 2020.08.08 |