简单Hashtable实现

 1     public class Map<TKey, TValue>
 2     {
 3         int listindex = 0;
 4 
 5         const int HASHSIZE = 100;//容量最大100
 6         Entry[] entries = new Entry[HASHSIZE];
 7         int[] buckets = new int[HASHSIZE];
 8         public Map()
 9         {
10             for (int i = 0; i < HASHSIZE; i++)
11                 buckets[i] = -1;
12         }
13         static void Calculate(TKey key, out int hashcode, out int code)
14         {
15             hashcode = key.GetHashCode();
16             code = (hashcode & 0x7fffffff) % HASHSIZE;
17         }
18         public bool TryGetValue(TKey key, out TValue value)
19         {
20             int index = FindEntry(key);
21             if (index == -1)
22             {
23                 value = default(TValue);
24                 return false;
25             }
26             else
27             {
28                 value = entries[index].Value;
29                 return true;
30             }
31         }
32         int FindEntry(TKey key)
33         {
34             int hashcode, code;
35             Calculate(key, out hashcode, out code);
36 
37             int index;
38             while ((index = buckets[code]) != -1)
39             {
40                 if (entries[index].HashCode == hashcode && entries[index].Key.Equals(key))
41                     return index;
42                 index = entries[index].ListIndex;
43             }
44             return -1;
45         }
46         public bool Add(TKey key, TValue value)
47         {
48             int hashcode, code;
49             Calculate(key, out hashcode, out code);
50 
51             if (FindEntry(key) != -1)
52                 return false;
53 
54             entries[listindex] = new Entry()
55             {
56                 ListIndex = buckets[code],
57                 HashCode = hashcode,
58                 Key = key,
59                 Value = value
60             };
61             buckets[code] = listindex;
62 
63             listindex++;
64             return true;
65         }
66         public bool Remove(TKey key)
67         {
68             int hashcode, code;
69             Calculate(key, out hashcode, out code);
70 
71             int index = FindEntry(key);
72             if (index == -1)
73                 return false;
74 
75             buckets[code] = entries[index].ListIndex;
76             entries[index] = null;
77             return true;
78         }
79         class Entry
80         {
81             public int ListIndex;
82             public int HashCode;
83             public TKey Key;
84             public TValue Value;
85         }
86     }

 

转载于:https://www.cnblogs.com/softcreator/articles/softcreator_8627561.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值