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     }

 

posted on 2013-04-04 21:24  阔然开朗  阅读(161)  评论(0编辑  收藏  举报