C # Hashtable Usage notes and the differences between Hashtable and HashMap

Source: Internet
Author: User

One, hash table (Hashtable) Brief

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 often used to quickly find, Key is case-sensitive at the same time, and value is used to store values corresponding to key. Key/value Key-value pairs in Hashtable are all object types, so hashtable can support any type of Key/value key-value pair.


Two, simple operation of hash table

Add a Key/value key value pair to the hash table: Hashtableobject.add (Key,value);
Remove a Key/value 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);
The following console program will contain all of the above actions:
Using System;
Using System.Collections; This namespace must be introduced when using Hashtable
Class Hashtable
{
public static void Main ()
{
Hashtable ht=new Hashtable (); Create a Hashtable instance
Ht. Add ("E", "E");//adding Key/value key-value pairs
Ht. ADD ("A", "a");
Ht. ADD ("C", "C");
Ht. ADD ("B", "B");
String s= (String) ht["A";
if (HT. Contains ("E"))//Determine if the hash table contains a specific key with a return value of TRUE or False
Console.WriteLine ("The E key:exist");
Ht. Remove ("C");//Remove a Key/value key-value pair
Console.WriteLine (ht["A"]);//Output a here
Ht. Clear ();//Remove all elements
Console.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:
For (DictionaryEntry de in HT)//HT as a Hashtable instance
{
Console.WriteLine (DE. Key);//de. Key corresponds to the Key/value key value pair key
Console.WriteLine (DE. Value);//de. Key corresponds to the value of the Key/value key
}


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 ArrayList (ht. Keys); Don't forget to import the System.Collections
Akeys. Sort (); Sort by alphabetical order
For (string skey in Akeys)
{
Console.Write (Skey + ":");
Console.WriteLine (Ht[skey]);//post-order output
}


the difference between Hashtable and HashMap
Hashtable is widely used, HashMap is the class used in the new framework to replace Hashtable, that is to say HashMap is recommended, do not use Hashtable. Maybe you think Hashtable is very useful, why not? Here is a simple analysis of their differences.

1.HashTable method is synchronous, HashMap is not synchronized, so in multi-threaded occasions to manually synchronize HashMap this difference is like vector and ArrayList.

2.HashTable does not allow null values (neither key nor value), HashMap allows null values (both key and value).

3.HashTable has a contains (object value) that functions like the Containsvalue (object value) function.

4.HashTable use Enumeration,hashmap with iterator. The above is only the surface of the different, their implementation is very different.

The default size of the hash array in 5.HashTable is 11, and the increment is old*2+1. The default size of the hash array in HashMap is 16, and must be a 2 index.

6. Using different hash values, Hashtable directly uses the object's Hashcode, which is the code:

int hash = Key.hashcode ();

int index = (hash & 0x7FFFFFFF)% Tab.length;

Instead, HashMap recalculates the hash value and uses and replaces the modulo:

int hash = hash (k);
int i = indexfor (hash, table.length);

static int hash (Object x) {
int h = X.hashcode ();
H + = ~ (h << 9);
H ^= (H >>> 14);
H + = (h << 4);
H ^= (H >>> 10);
return h;
}

static int indexfor (int h, int length) {
Return H & (LENGTH-1);
}
These are just some of the more prominent differences, of course, their implementation is still a lot of different, such as hashmap to null operation.  

The difference between Hashtable and HashMap:
1.Hashtable is a subclass of dictionary, and HashMap is an implementation class of the map interface;
The methods in 2.Hashtable are synchronous, and the methods in HashMap are not synchronized by default. That is, in a multithreaded application, it is safe to use Hashtable without specialized operations, and for HashMap, an additional synchronization mechanism is required. However, the HashMap synchronization problem can be solved by a static method of collections:
Map Collections.synchronizedmap (map m)
This method returns a synchronized map that encapsulates all the methods of the underlying hashmap, making the underlying hashmap secure even in multi-threaded environments.
3. In HashMap, NULL can be used as a key with only one key, and one or more keys can have a value of NULL. When the Get () method returns a null value, it can indicate that the key is not in the HashMap, or that the value corresponding to the key is null. Therefore, the get () method cannot be used in HashMap to determine whether a key exists in HashMap and should be judged by the ContainsKey () method.
Hashtable inherits from the dictionary class, and HashMap is an implementation of the map interface introduced by Java1.2

HashMap allows NULL to be a entry key or value, and Hashtable does not allow

There is, HashMap hashtable contains method removed, changed to Containsvalue and ContainsKey. Because the contains method is easy to cause misunderstanding.
The biggest difference is that the method of Hashtable is synchronize, and HashMap is not, in
When multiple threads access Hashtable, they do not need to implement synchronization for their methods, while HashMap
You must provide external synchronization for it.

The Hash/rehash algorithms used by Hashtable and HashMap are probably the same, so there is no big difference in performance.

C # Hashtable Usage notes and the differences between Hashtable and HashMap

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.