-
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://asp-net.blogbus.com/logs/39632643.html
原文地址:http://www.itstrike.cn/Home/Article/CSharp-collection-class-with-thread-safe-HashTable
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:
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<int, string> fruits = new System.Collections.Generic.Dictionary<int, string>();

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.");
}
ArrayList是一维变长数组,内部值为object类型,效率一般:

//ArrayList
System.Collections.ArrayList list = new System.Collections.ArrayList();
list.Add(1);//object type
list.Add(2);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list);
}
随机文章:
2009-11-04 volumn18 头发 2009-11-04年轻十岁:需要做的和不能做的 2008-12-13你的微笑是开心的传染源 2008-12-11Asp.Net入门学习 2008-12-11GridView技巧大全 2008-12-11
收藏到:Del.icio.us
引用地址:
<< Struts2的零配置 | 首页 |







