The difference between HashTable, HashSet and dictionary

Source: Internet
Author: User

Hashtable and dictionaryhttp://www.cnblogs.com/bingzisky/archive/2008/11/10/1330493.htmlhttp://www.cnblogs.com/ Akwwl/p/3680376.html

Hashtable and Dictionary <k, v> type
1: Dictionary is recommended in single-threaded applications, with a generic advantage, with faster read speeds and fuller capacity utilization.
2: The recommended use of Hashtable in multithreaded programs, the default Hashtable allows single-threaded writes, multithreaded reads, and Hashtable further calls to the Synchronized () method to obtain a fully thread-safe type. While Dictionary is non-thread-safe, it must be protected by the use of the lock statement, and the efficiency is greatly reduced.
3:dictionary has the ability to arrange data in the order in which they are inserted (note: But the order is disrupted when the call to remove () is removed), so it is convenient to use Dictionary in situations where the order needs to be reflected.

Hashtable classes and dictionary< (of < (TKey, tvalue>) >) Generic classes Implement IDictionary interfaces

dictionary< (Of < (TKey, tvalue>) >) Generic classes also implement idictionary< (of < (TKey, tvalue>) >) generic interfaces. Therefore, each element in these collections is a key/value pair.

dictionary< (Of < (TKey, tvalue>) >) The same functionality as the Hashtable class
For value types, the performance of dictionary< (of < (TKey, tvalue>) >) for a particular type (excluding Object) is better than Hashtable because the Hashtable element is of type Object, Therefore, boxing and unboxing operations typically occur when a value type is stored or retrieved.

HashTable ht=new HashTable ();//Implement IDictionary interface
Ht. ADD (1, "A");
Ht. ADD (2, "B");
Ht. ADD (3, "C");
foreach (DictionaryEntry de in HT)//hashtable returns the DictionaryEntry type
{
Beh Key;
Beh Value;
}

Dictionary<int,string> mydictionary=new dictionary<int,string> ();//Implement IDictionary interface, idictionary<t Key,t Value> Class
Mydictionary.add (1, "a");
Mydictionary.add (2, "B");
Mydictionary.add (3, "C");
foreach (int i in Mydictionary.keys)
{
Console.WriteLine ("Key=" +i+ "value=" +mydictionary);
}
Or
foreach (keyvaluepair<string, double> temp in mydictionary)//Return is keyvaluepair<string, double> generic array
{
Temp. Key;
Temp. Value;
}

When using an indexer to fetch a value, an exception is thrown if the key does not exist
Try
{
Console.WriteLine ("Non-existent key" "FFF" "Key value is:" + mydic["fff"]);
}
catch (KeyNotFoundException ex)
{
Console.WriteLine ("The key was not found" throws an exception: "+ ex.) Message);
}
The method of solving the above exception is to use Contarnskey () to determine when the key is present, if it is often desirable to get the health of the TryGetValue method to obtain the corresponding key value in the collection
String value = "";
if (Mydictionary.trygetvalue ("fff", out value))
{
Console.WriteLine (the key value for "non-existent key" "FFF" "is:" + value);
}
Else
{
Console.WriteLine ("No key value found for the corresponding key");
}

The following uses foreach to iterate over the key-value pairs
Generic constructs are used to store health-value pairs
foreach (keyvaluepair<string, string> temp in mydictionary)
{
Console.WriteLine (temp. Key, temp. Value);
}
Get Worthy Collection
foreach (string s in mydictionary.values)
{
Console.WriteLine ("Value" + s);
}
Get It worth another way
Dictionary<string, String> ValueCollection values = mydictionary.values;
foreach (string s in values)
{
Console.WriteLine ("Value:" + s);
}
Common properties and methods are as follows: Common properties
Property Description
Comparer
Gets the iequalitycomparer used to determine whether the keys in the dictionary are equal.
Count
Gets the number of key/value pairs contained in the dictionary.
Item
Gets or sets the value associated with the specified key.
Keys
Gets the collection that contains the keys in the dictionary.
Values
Gets a collection that contains the values in the dictionary.

Common method and Method description
Add Mydictionary.add (string key,double value);
Adds the specified key and value to the dictionary.

Clear mydictionary.clear ();
Remove all keys and values from the dictionary.

ContainsKey Mydictionary.containskey (string key);
Determines whether the dictionary contains the specified key.
Containsvalue Mydictionary.containsvalue (Double value)
Determines whether the dictionary contains a specific value.

Equals
is overloaded. Determines whether two instances of Object are equal. (Inherit from Object.) )

GetEnumerator mydictionary.getenumerator (New dictionary<string,double > ("AAA", 11.11);
Returns an enumerator that iterates through the dictionary.

GetHashCode
Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures such as hash tables. (Inherit from Object.) )

GetObjectData
Implements the System.Runtime.Serialization.ISerializable interface and returns the data required to serialize the dictionary instance.

GetType
Gets the Type of the current instance. (Inherit from Object.) )

OnDeserialization
Implements the System.Runtime.Serialization.ISerializable interface and raises the deserialization event after deserialization is complete.

ReferenceEquals
Determines whether the specified object instance is the same instance. (Inherit from Object.) )

Remove
Removes the value of the specified key from the dictionary.

Tostring
Returns a String that represents the current object. (Inherit from Object.) )

TryGetValue mydictionary.trygetvalue (string key,out double value); note Because the use of out all must be declared in front of a variable

namely: Double Valuetest

if (! Mydictionary.trygetvalue (key,out valuetest))

valuetest= 0.0; If there is no such key value then valuetest=0.0, or the real value is assigned to valuetest

------------------------------------------------------------

 1.HashTable

A hash table (HashTable) represents a collection of key/value pairs. In the. NET Framework, Hashtable is a container provided by the System.Collections namespace that handles and behaves like Key-value key-value pairs, where key is usually used for quick lookups, and key is case-sensitive; value is used to store the value corresponding to key. Key-value Key-value pairs in Hashtable are all object types, so hashtable can support any type of KeyValue key-value pair, and any non-null object can be used as a key or a value.

Add a key/key value pair to the hash table: Hashtableobject.add (key,);

Remove a key/key value pair in the hash table: Hashtableobject.remove (key);

Remove all elements from the hash table: Hashtableobject.clear ();

Determines whether a hash table contains a specific key key:HashtableObject.Contains (key);

  2.HashSet

The Hashset<t> class is designed to perform high-performance set operations such as intersection, set, and difference set for two sets. The collection contains a set of elements that do not recur and have no attribute order, and HashSet refuses to accept duplicate objects.

Some of the features of hashset<t> are as follows:

A. The values in hashset<t> cannot be duplicated and have no order.

B. The capacity of the hashset<t> is automatically added as needed.

  3.Dictionary

Dictionary represents a collection of keys and values.

Dictionary<string, string> is a generic

He has a set of functions that can sometimes be seen as an array.

His structure is this: Dictionary<[key], [value]>

His feature is that the deposit object is required to be stored with the [key] value one by one in the generic

To find the corresponding value by a certain [key]

  The difference between 4.HashTable and dictionary:

(1). Hashtable does not support generics, while dictionary supports generics.

(2). The Hashtable element is of type Object, so boxing and unpacking is usually the case when storing or retrieving a value type, so you may need to do some type conversion, and it can be time-consuming to int,float these value types for boxing.

(3). Dictionary is recommended in single-threaded programs, with a generic advantage, with faster read speeds and fuller capacity utilization. Hashtable is recommended in multithreaded programs, the default Hashtable allows single-threaded writes, multithreaded reads, and further calls to the Hashtable Synchronized () method to obtain a fully thread-safe type. While Dictionary is non-thread-safe, it must be protected by the use of the lock statement, and the efficiency is greatly reduced.

(4) When passing the code test found that key is an integer type dictionary efficiency than hashtable faster, if key is a string type, dictionary efficiency is not hashtable fast.

static void Intmethod () {int count = 1000000;            Dictionary<int, int> Dictionary = new Dictionary<int, int> ();            Hashtable Hashtable = new Hashtable (); for (int i = 0; i < count; i++) {dictionary.                ADD (I,i); Hashtable.            ADD (I,i);            } Stopwatch Stopwatch = Stopwatch.startnew ();            for (int i = 0; i < count; i++) {int value = Dictionary[i]; } stopwatch.            Stop (); Console.WriteLine (stopwatch.            Elapsedmilliseconds);            Stopwatch = Stopwatch.startnew ();            for (int i = 0; i < count; i++) {Object value = Hashtable[i]; } stopwatch.            Stop (); Console.WriteLine (stopwatch.         Elapsedmilliseconds);            } static void Methodstring () {int count = 1000000; dictionary<string, string> Dictionary = new DIctionary<string, string> ();            Hashtable hashtable=new Hashtable (); for (int i = 0; i < count; i++) {dictionary.                ADD (i.ToString (), "AAA"); Hashtable.            ADD (i.ToString (), "AAA");            } Stopwatch Stopwatch = Stopwatch.startnew ();            for (int i = 0; i < count; i++) {string value=dictionary[i.tostring ()]; } stopwatch.            Stop (); Console.WriteLine (stopwatch.            Elapsedmilliseconds);            Stopwatch = Stopwatch.startnew ();            for (int i = 0; i < count; i++) {Object value = hashtable[i.tostring ()]; } stopwatch.            Stop (); Console.WriteLine (stopwatch. Elapsedmilliseconds);


The difference between HashTable, HashSet and dictionary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.