自寫一個模仿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存放的地址。