Hashtable集合中的元素以Key/Value方式存在。Key用來(lái)快速查找;Value用于存儲對應于Key的值。值得注意的是Key和Value均為object類(lèi)型。
二、對Hashtable操作
對Hashtable操作包括:
1)添加集合元素
2)檢索集合元素
3)遍歷
4)排序集合元素
5)修改集合元素
6)刪除集合元素
以下簡(jiǎn)單的控制臺程序實(shí)現上述操作(C#)
{
using System;
using System.Collections;
class sample
{
static void Main(string[] args)
{
// 創(chuàng )建Hashtable集合
Hashtable ht =new Hashtable();
// 向集合中添加 key/value 對
ht.Add("1", "apple");
ht.Add("2", "orange");
ht.Add("3","strawberry");
ht.Add("0","fruit");
// 通過(guò) key 找到 value
Console.WriteLine("通過(guò) key 找到 value");
string v=(string)ht["1"];
Console.WriteLine(v);
// 遍歷集合
Console.WriteLine("\n遍歷集合");
foreach( DictionaryEntry de in ht)
Console.WriteLine("Key=\"{0}\"\tValue=\"{1}\"",de.Key.ToString(), de.Value.ToString());
// 對集合進(jìn)行排序
Console.WriteLine("\n對集合進(jìn)行排序");
ArrayList aKeys=new ArrayList(ht.Keys);
aKeys.Sort();
foreach(string key in aKeys)
Console.WriteLine("Key=\"{0}\"\tValue=\"{1}\"",key, ht[key].ToString());
// 修改指定 key 的 value
ht["0"]="Animal";
ht["1"]="Monkey";
ht["2"]="Horse";
ht["3"]="Donkey";
Console.WriteLine("\n遍歷修改后集合");
foreach( DictionaryEntry de in ht)
Console.WriteLine("Key=\"{0}\"\tValue=\"{1}\"",de.Key.ToString(), de.Value.ToString());
// 刪除集合元素
ht.Remove("2");
ht.Remove("1");
Console.WriteLine("\n遍歷刪除元素后集合");
foreach( DictionaryEntry de in ht)
Console.WriteLine("Key=\"{0}\"\tValue=\"{1}\"",de.Key.ToString(), de.Value.ToString());
// 刪除所以集合元素
ht.Clear();
}
}
}
聯(lián)系客服