Hashtable
Hashtable的本质
Hashtable 又称散列表,是基于键的哈希代码组织起来的键值对
主要作用是提高数据查询效率,使用键来访问集合中的元素
//申明
Hashtable hashtable = new Hashtable();
//增加
//不管是键还是值都是object类型,所以键和值都可以存储任何内容
//不能出现相同键,值无所谓
hashtable.Add(1,"123");
hashtable.Add("123",2);
//删除
//只能通过键去删除
hashtable.Remove(1);
//如果键不存在,就无事发生
//清空
hashtable.Clear();
//查
//通过键查看值,如果不存在键则会返回空
Console.WriteLine(hashtable[1]);
//查询是否存在
//根据键检测
if(hashtable.Contains(1))
{
Console.WriteLine("存在键为1的键值对");
}
if(hashtable.ContainsKey(1))
{
Console.WriteLine("存在键为1的键值对");
}
//根据值检测
if(hashtable.ContainsValue(2))
{
Console.WriteLine("存在值为2的键值对");
}
//改
//只能修改值内容,不能修改键
hashtable[1]=200;
//得到键值对的对数
Console.WriteLine(hashtable.Count);
//遍历所有键
foreach (object item in hashtable.Keys)
{
Console.WriteLine(item);//得到键
Console.WriteLine(hashtable[item])//得到值
}
//遍历所有值
foreach (object item in hashtable.Values)
{
Console.WriteLine(item);//得到值
}
//键值对一起遍历
foreach (DictionaryEntry item in hashtable)
{
Console.WriteLine(item.Key);//得到键
Console.WriteLine(item.Value);//得到值
}
//迭代器遍历
IDictionaryEnumerator myEnumerator hashtable.GetEnumerator();
bool flag = myEnumerator.MoveNext();
while(flag)
{
Console.WriteLine(myEnumerator.Key);
Console.WriteLine(myEnumerator.Value);
flag = myEnumerator.MoveNext();
}
也存在装箱拆箱
习题
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hashtable习题
{
//因为管理器一般都是唯一的,所以做成单例模式对象(单例设计?
internal class MonsterManage
{
private static MonsterManage instance = new MonsterManage();
Hashtable hashtable=new Hashtable();
private MonsterManage()
{
}
public static MonsterManage Instance
{
get
{
return instance;
}
}
private int monsterID = 0;
public void Add(int id)
{
Monster monster = new Monster(monsterID);
++monsterID;
hashtable.Add(monster.id, monster);
}
public void Remove(int id)
{
if(hashtable.ContainsKey(id))
{
hashtable.Remove(id);
}
}
}
class Monster
{
public int id;
public Monster(int id)
{
this.id = id;
}
}
}

浙公网安备 33010602011771号