一、Hashtable概述
Hashtable集合中的元素以Key/Value方式存在。Key用来快速查找;Value用于存储对应于Key的值。值得注意的是Key和Value均为object类型。
二、对Hashtable操作
对Hashtable操作包括:
1)添加集合元素
2)检索集合元素
3)遍历
4)排序集合元素
5)修改集合元素
6)删除集合元素
以下简单的控制台程序实现上述操作(C#)
namespace hashtableOp
{
using System;
using System.Collections;
class sample
{
{
// 创建Hashtable集合
Hashtable ht =new Hashtable();
// 向集合中添加 key/value 对
ht.Add("1", "apple");
ht.Add("2", "orange");
ht.Add("3","strawberry");
ht.Add("0","fruit");
Console.WriteLine("通过 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());
// 对集合进行排序
Console.WriteLine("\n对集合进行排序");
ArrayList aKeys=new ArrayList(ht.Keys);
aKeys.Sort();
foreach(string key in aKeys)
Console.WriteLine("Key=\"{0}\"\tValue=\"{1}\"",key, ht[key].ToString());
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();
}
}
}
{
using System;
using System.Collections;
class sample
{
static void Main(string[] args)
{
// 创建Hashtable集合
Hashtable ht =new Hashtable();
// 向集合中添加 key/value 对
ht.Add("1", "apple");
ht.Add("2", "orange");
ht.Add("3","strawberry");
ht.Add("0","fruit");
// 通过 key 找到 value
Console.WriteLine("通过 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());
// 对集合进行排序
Console.WriteLine("\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();
}
}
}