One, hash table (Hashtable) Brief
In the. NET framework, Hashtable is a container provided by the System.Collections namespace,
A key-value pair that handles and behaves like Key/value, where key is often used to quickly find,
Key is case-sensitive at the same time, and value is used to store values corresponding to key.
The Key/value key-value pairs in Hashtable are all object types,
So Hashtable can support any type of Key/value key-value pair.
Second, the simple operation of the hash table
Add a Key/value key-value pair to the hash table:
Hashtableobject.add (Key,value);
Remove a Key/value key-value pair from the hash table:
Hashtableobject.remove (key);
Remove all elements from the hash table:
Hashtableobject.clear ();
Determine if the hash table contains a specific key:
Hashtableobject.contains (key);
The following console program contains all of the above examples of operations:
usingSystem;usingSystem.Collections;//This namespace must be introduced when using Hashtableclasshashtable{ Public Static voidMain () {Hashtable HT=NewHashtable ();//Create a Hashtable instanceHt. ADD ("E","e");//adding Key/value Key-value pairsHt. ADD ("A","a"); Ht. ADD ("C","C"); Ht. ADD ("B","b"); stringS= (string) ht["A"]; if(HT. Contains ("E"))//determines whether the hash table contains a specific key with a return value of TRUE or falseConsole.WriteLine ("The E key:exist"); Ht. Remove ("C");//Remove a Key/value key-value pairConsole.WriteLine (ht["A"]);//output a hereHt. Clear ();//Remove all elementsConsole.WriteLine (ht["A"]);//there will be no output here }}
Third, traverse the hash table
Traversing a hash table requires the use of DictionaryEntry Object, the code is as follows:
foreach inch // HT is a Hashtable instance {Console.WriteLine (DE. Key); // de. Key corresponds to the Key/value key value to key Console.WriteLine (DE. Value); // de. Key corresponds to Key/value value}
Four, sort the hash table
Sorting the hash table here is defined as the key in the Key/value key-value pair is rearranged by certain rules, but in practice this definition is not possible because we cannot rearrange the key directly in Hashtable, If you need hashtable to provide output for some sort of rule, you can use a workaround:
ArrayList akeys=New// Don't forget to import system.collections// sort in alphabetical order foreach (stringin":"); Console.WriteLine (Ht[skey]); // post-order output }
Hashtable cannot be sorted, but treemap can be used instead of Hashtable.
TreeMap ts=NewTreeMap (); Ts.put (NewInteger ("1"),"Aaa1"); Ts.put (NewInteger ("3"),"Aaa3"); Ts.put (NewInteger ("2"),"Aaa2"); Ts.put (NewInteger (" the"),"aaa500"); Ts.put (NewInteger (" -"),"aaa2000"); Set St=Ts.keyset (); for(Iterator i=st.iterator (); I.hasnext ();) {System. out. println (TS.Get(I.next ()));}
Assignment, value, traversal, sort operations for Hashtable in C #