hashtable 与字典表Dictionary

来源:互联网 发布:php短网址生成源码 编辑:程序博客网 时间:2024/05/10 05:39

转载地址:http://blog.csdn.net/aa2397199142/article/details/52231823


哈希表Hashtable与字典表Dictionary<K,V>的比较

哈希表,名-值对。类似于字典(比数组更强大)。哈希表是经过优化的,访问下标的对象先散列过。如果以任意类型键值访问其中元素会快于其他集合。GetHashCode()方法返回一个int型数据,使用这个键的值生成该int型数据。哈希表获取这个值最后返回一个索引,表示带有给定散列的数据项在字典中存储的位置。由于Hashtable每个元素都是一个键/值对,因此元素类型既不是键的类型,也不是值的类型,而是DictionaryEntry类型。Dictionary<Tkey,Tvalue>是Hastbale的泛型实现由于 Dictionary 是键和值的集合,因此元素类型并非键类型或值类型。相反,元素类型是键类型和值类型的 KeyValuePair 

Hashtable  Dictionary <K, V> 类型 
1
单线程程序中推荐使用 Dictionary, 有泛型优势且读取速度较快容量利用更充分.

2
多线程程序中推荐使用 Hashtable, 默认的 Hashtable 允许单线程写入多线程读取 Hashtable 进一步调用 Synchronized() 方法可以获得完全线程安全的类型Dictionary 非线程安全必须人为使用lock 语句进行保护效率大减.
3
Dictionary 按插入顺序排列数据的特性 (但当调用 Remove() 删除过节点后顺序被打乱), 因此在需要体现顺序的情境中使用 Dictionary 能获得一定方便.

HashTable中的key/value均为object类型,由包含集合元素的存储桶组成。存储桶是 HashTable中各元素的虚拟子组,与大多数集合中进行的搜索和检索相比,存储桶可令搜索和检索更为便捷。每一存储桶都与一个哈希代码关联,该哈希代码是使用哈希函数生成的并基于该元素的键。HashTable的优点就在于其索引的方式,速度非常快。如果以任意类型键值访问其中元素会快于其他集合,特别是当数据量特别大的时候,效率差别尤其大。

HashTable的应用场合有:做对象缓存,树递归算法的替代,和各种需提升效率的场合

 //Hashtable sample
System.Collections.Hashtable ht = new
 System.Collections.Hashtable(); 
//--Be careful: Keys can't be duplicated(重复), and can't be null----
ht.Add(1"apple"
);
ht.Add(
2"banana"
);
ht.Add(
3"orange"
); 
//Modify item value:
if(ht.ContainsKey(1
))
ht[
1] = "appleBad"

//The following code will return null oValue, no exception
object oValue = ht[5
]; 
//traversal遍历 1:
foreach (DictionaryEntry de in
 ht)
{
Console.WriteLine(de.Key);
Console.WriteLine(de.Value);

//traversal 2: IDictionaryEnumerator只是一个强类型的枚举器,可以通过inherits继承IEnumerator实现功能扩展
System.Collections.IDictionaryEnumerator d = ht.GetEnumerator();//枚举
while
 (d.MoveNext())
{
Console.WriteLine(
"key{0} value{1}"
, d.Entry.Key, d.Entry.Value);

//Clear items
ht.Clear();


Dictionary
HashTable内部实现差不多,但前者无需装箱拆箱操作,效率略高一点。

 //Dictionary sample
System.Collections.Generic.Dictionary<intstring> fruits = newSystem.Collections.Generic.Dictionary<intstring
>(); 
fruits.Add(
1"apple"
);
fruits.Add(
2"banana"
);
fruits.Add(
3"orange"
); 
foreach (int i in
 fruits.Keys)
{  Console.WriteLine("key{0} value{1}", i, fruits);  }
if (fruits.ContainsKey(1
))
{
Console.WriteLine(
"contain this key."
);
}

HashTable是经过优化的,访问下标的对象先散列过,所以内部是无序散列的,保证了高效率,也就是说,其输出不是按照开始加入的顺序,Dictionary遍历输出的顺序,就是加入的顺序,这点与Hashtable不同。如果一定要排序HashTable输出,只能自己实现:

 //Hashtable sorting
System.Collections.ArrayList akeys = new System.Collections.ArrayList(ht.Keys); 
//from Hashtable
akeys.Sort(); 
//Sort by leading letter
foreach (string skey in
 akeys)
{
Console.Write(skey + 
":"
);
Console.WriteLine(ht[skey]);
}

HashTable与线程安全

为了保证在多线程的情况下的线程同步访问安全,微软提供了自动线程同步的HashTable:

如果 HashTable要允许并发读但只能一个线程写要这么创建 HashTable实例:

 //Thread safe HashTable
System.Collections.Hashtable htSyn = System.Collections.Hashtable.Synchronized(newSystem.Collections.Hashtable());

这样, 如果有多个线程并发的企图写HashTable里面的 item, 则同一时刻只能有一个线程写其余阻塞对读的线程则不受影响。

另外一种方法就是使用lock语句,但要lock的不是HashTable,而是其SyncRoot虽然不推荐这种方法,但效果一样的,因为源代码就是这样实现的:

private static System.Collections.Hashtable htCache = new System.Collections.Hashtable ();

public static void AccessCache ()

lock ( htCache.SyncRoot ) {htCache.Add ( "key", "value" ); }

}

//Is equivalent to 等同于 (lock is equivalent to Monitor监听器.Enter and Exit()

public static void AccessCache (){

System.Threading.Monitor.Enter ( htCache.SyncRoot );

try {     htCache.Add ( "key", "value" );   }

        finally System.Threading.Monitor.Exit ( htCache.SyncRoot );   }

}


索引

索引器类似于属性,不同之处在于它们的get访问器采用参数要声明类或结构上的索引器,使用this关键字

/// <summary>
/// 存储星期几的类。声明了一个get访问器,它接受字符串,并返回相应的整数
/// </summary>
public class 星期
{
    public string[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
    //索引器 它接受星期几的字符串,将它作为索引index
    public int this[string day]
    {
       //get访问器 并返回相应的整数
        get
       {
            int i = 0;
            foreach (var item in weeks)
            {
                if (item == day)
                {
                    return i;
                }
                i++;
            }
            //没找到返回-1
            return -1;
        }
    }
}

DataTable的介绍

DataTable 的最大列数可以到 Int32.MaxValue,或者2,147,483,647,DataTable可存储的最大行数是 16777216(经过测试datatable的行数不受16777216限制,与机器内存有关)。但由于可用内存的限制,在未达到最大列数的时候,可能会抛出 OutOfMemoryException 的异常。

详细内容见: http://www.360doc.com/content/11/0202/07/19147_90396500.shtml  DataTable使用的基本语法

https://msdn.microsoft.com/zh-cn/library/system.data.datatable.aspx 微软官方文档