国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

自寫一個模仿Dictionary與Foreach的實現及心得總結

2024-07-10 12:46:25
字體:
來源:轉載
供稿:網友
自己寫一個類模仿Dictionary實現
a、自定義字典類MyDic
代碼如下:
using System.Collections.Generic;
namespace _10_自己寫Dictionary {
class KeyValuePair {
public KeyValuePair() {
}
public KeyValuePair(string key, string value) {
this.key = key;
this.value = value;
}
private string key;
public string Key {
get {
return key;
}
set {
key = value;
}
}
private string value;
public string Value {
get {
return this .value;
}
set {
this.value = value ;
}
}
}
class MyDic {
List<KeyValuePair > list = new List<KeyValuePair >();
public void Add(string key, string value) {
list.Add( new KeyValuePair (key, value));
}
public bool ContainsKey(string key) {
bool res = false ;
foreach(KeyValuePair item in list) {
if(item.Key == key) {
res = true;
break;
}
}
return res;
}
}
}

b、調用測試
代碼如下:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace _10_自己寫Dictionary {
class Program {
static void Main(string[] args) {
//Dictionary方法實現
Dictionary<string , string> dic = new Dictionary <string, string>();
string[] filecon = File .ReadAllLines("英漢詞典TXT格式.txt", Encoding.Default);
for(int i = 0; i < filecon.Count(); i++) {
string[] arr = filecon[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if(!dic.ContainsKey(arr[0])) {
dic.Add(arr[0], arr[1]);
}
}
Stopwatch sw = new Stopwatch();
sw.Start();
dic.ContainsKey( "china");
sw.Stop();
Console.WriteLine(sw.Elapsed);//00:00:00:0000055;
//自己寫的list實現
MyDic mydic = new MyDic();
string[] filecon2 = File .ReadAllLines("英漢詞典TXT格式.txt", Encoding.Default);
for(int i = 0; i < filecon2.Count(); i++) {
string[] arr = filecon2[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if(!mydic.ContainsKey(arr[0])) {
mydic.Add(arr[0], arr[1]);
}
}
Stopwatch sw2 = new Stopwatch();
sw2.Start();
mydic.ContainsKey( "china");
sw2.Stop();
Console.WriteLine(sw2.Elapsed);//00:00:00:0001287;慢了多少倍!!! 因為dictionary比list多了字典目錄
Console.Read();
}
}
}

b中測試結果顯示自己模仿的沒有.Net FrameWork提供的快 為什么呢?

答:Dictionary中有一個存儲鍵值對的區域,這個區域的每個存儲單元有地址編號,根據hashCode算法,計算key的值的鍵值對應該存儲的地址,將鍵值對放入指定的地址即可。查找的時候首先計算key的地址,就可以找到數據了。根據key找房間號,而不是逐個房間找。(*)或者說:當把一個kvp,采用一個固定算法(散列算法)根據key來計算這個kvp存放的地址。取的時候也是根據要找的key可以快速算出kvp存放的地址。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 涡阳县| 丰县| 岑巩县| 东兴市| 天镇县| 岳普湖县| 仁化县| 苏尼特右旗| 民乐县| 淮南市| 仪征市| 邯郸市| 于田县| 柘城县| 闸北区| 利川市| 山阴县| 中江县| 深州市| 潞西市| 南开区| 旌德县| 镇平县| 额敏县| 绥滨县| 弋阳县| 富蕴县| 达孜县| 田阳县| 新安县| 新泰市| 章丘市| 鄄城县| 香港| 贞丰县| 临西县| 阿拉善右旗| 临清市| 汝州市| 棋牌| 深州市|