转自:http://bbs.csdn.net/topics/390034346

在java中像ArrayList,HashMap都是现成的,在java.util包中,用的时候直接import java.util.*就行了。

前几天写了一c版的ArrayList,同时欢迎大家指出问题:
http://topic.csdn.net/u/20120429/18/4ab4bc02-2496-4d3c-8151-1cbe51e6fe9d.html?seed=425415324&r=78416084

今天有空,也为了练习一下c,我就参照着jdk中的HashMap源码,写了一个c版的HashMap,这个HashMap多少有点泛型的特征<E>。

关于这个HashMap,现在有一个困惑,在hashmap_remove()中,要不要在返回前free()?
直接上代码,接受大家的检阅(欢迎大家指出问题):

hashmap.h

C/C++ code

 

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#ifndef HASHMAP_H_INCLUDED
#define HASHMAP_H_INCLUDED
 
//HashMap中的链表
typedef struct _entry
{
    int hash;
    void *key;
    void *value;
    struct _entry *next; //单向链表
 
} *Entry;
 
//主要用于hashmap_keySet()
typedef struct _hashmapset
{
    void *key;
    struct _hashmapset *next;
 
} *HashMapSet;
 
//hashmap 结构
typedef struct _hashmap
{
    int K_E; //类似java中的泛型
    int V_E; //类似java中的泛型
    int size;
    int capacity; //当前容量
    int threshold; //门槛
    float factor; //扩展因子,当空间不够用时
    Entry table;
 
} *HashMap;
 
#ifndef E_H_INCLUDED
#define E_H_INCLUDED
enum E{E_STRING,E_INT,E_OBJECT}; //枚举类型
#endif // E_H_INCLUDED
 
void *hashmap_init(int k,int v); //初始化
 
void *hashmap_put(HashMap this,void *k,void *v); //在此映射中关联指定值与指定键。
 
void *hashmap_get(HashMap this,void *k); //返回指定键在此标识哈希映射中所映射的值,如果对于此键来说,映射不包含任何映射关系,则返回 null
 
void *hashmap_remove(HashMap this,void *k); //如果此映射中存在该键的映射关系,则将其删除。
 
HashMapSet hashmap_keySet(HashMap this); //返回此映射中所包含的键的 set 视图。
 
void hashmap_clear(HashMap this); //从此映射中移除所有映射关系。
 
void hashmap_free(HashMap this); //释放内存
 
 
#endif // HASHMAP_H_INCLUDED

回复次数:7

关注
test_lockxxx
test_lockxxx
等级:
#1 得分:0回复于: 2012-05-04 06:17:58
hashmap.c

C/C++ code

 

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hashmap.h"
 
//参考了java的HashMap.java中的hash算法
static int hash(int h)
{
    /*
    //java
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
    */
 
    unsigned int x = h; //由于要无符号右移,左边补0
    x ^= (x >> 20) ^ (x >> 12);
    return x ^ (x >> 7) ^ (x >> 4);
 
}
 
//参考了java的HashMap.java中的indexFor()
static int indexFor(int h, int length)
{
    return h & (length-1);
}
 
//字符串的hashcode,改写java的String.hashCode();
static int stringHashCode(char *pStr)
{
    int size = strlen(pStr);
 
    if(size == 0)
    {
        return 0;
    }
    else
    {
        int i,h=0;
        for(i=0; i<size; i++)
        {
            h = 31 * h + *pStr;
            pStr++;
        }
 
        return h;
    }
}
 
 
//扩大容量
static void resize(HashMap this,int newCapacity)
{
    //printf("resize 前, capacity:%d,threshold:%d\n",this->capacity,this->threshold);
 
    int oldCapacity = this->capacity;
 
    Entry newTable = malloc(sizeof(struct _entry) * newCapacity);
 
    //初始化为NULL;
    int i;
    for(i=0; i<newCapacity; i++)
    {
        (newTable + i)->next = NULL;
    }
 
    //由src指向地址为起始地址的连续n个字节的数据复制到以dest指向地址为起始地址的空间内。
    //由于hash表的容量扩大,indexFor(int hash,int length)由于length改变,返回值也将改变,所以此处不能简单的使用memcpy
    //memcpy(newTable,this->table,sizeof(struct _entry) * oldCapacity);
 
    //重新确定新的位置indexFor(....)
    //以下实现参照java的HashMap.java中的void transfer(Entry[] newTable)部分
    int m,n;
    for(m=0; m<oldCapacity; m++)
    {
        Entry e = (this->table + m)->next;
 
        if(e!=NULL)
        {
            do
            {
                Entry next = e->next;
 
                n = indexFor(e->hash,newCapacity);
 
                e->next = (newTable + n)->next;
 
                (newTable + n)->next = e;
 
                e = next;
            }
            while(e!=NULL);
        }
    }
 
    this->table = newTable;
    this->capacity = newCapacity;
    this->threshold = (int)(newCapacity * this->factor);
 
    //printf("resize 后, capacity:%d,threshold:%d\n\n",this->capacity,this->threshold);
}
 
//添加一个结点到链表中
static void addEntry(HashMap this,void *k,void *v,int hashCode,int i)
{
    Entry e = this->table + i; //先定位到一个链表的head 结点
 
    //添加到链表中
    do
    {
        if(e->next == NULL)
        {
            //新的结点
            Entry item = malloc(sizeof(struct _entry));
            item->hash = hashCode;
            item->key = k;
            item->value = v;
            item->next = NULL;
 
            e->next = item; //加入链表中
 
            break;
        }
    }
    while((e = e->next) != NULL);
 
    this->size++; //size + 1
 
    if (this->size >= this->threshold)
    {
        resize(this,2 * this->size); //扩大一倍容量
    }
}
 
 
 
//初始化
void *hashmap_init(int k_e,int v_e)
{
    HashMap map = malloc(sizeof(struct _hashmap));
    map->K_E = k_e;
    map->V_E = v_e;
    map->size = 0;
    map->capacity = 16;
    map->factor = 0.75f;
    map->threshold = (int)(map->capacity * map->factor);
 
    map->table = malloc(sizeof(struct _entry) * map->capacity);
 
    //初始化为NULL
    int i;
    int capacity = map->capacity;
    for(i=0; i<capacity; i++)
    {
        (map->table+i)->next = NULL; //初始化
 
        //printf("init %d address:%d\n",i,map->table + i);
    }
 
    //printf("capacity address:%d\n",&map->capacity);
 
    return map;
}
 
//在此映射中关联指定值与指定键。
void *hashmap_put(HashMap this,void *k,void *v)
{
    int hashCode;
    if(this->K_E == E_STRING)
    {
        hashCode = hash(stringHashCode(k));
 
        //printf("-----------%s:%d\n",k,hashCode);
    }
    else if(this->K_E == E_INT)
    {
        hashCode = hash(k);
    }
    else
    {
        hashCode = hash(k);
    }
 
    int i = indexFor(hashCode,this->capacity);
    Entry e;
 
    if(this->K_E == E_STRING || this->K_E == E_INT)
    {
        for(e = this->table + i,e=e->next; e!=NULL; e=e->next)
        {
            if((e->hash == hashCode) && (e->key == k || strcmp(e->key,k) == 0))
            {
                void *oldValue = e->value; //取原来的旧的值
                e->value = v; //设置新值
 
                return oldValue; //返回旧值
            }
        }
    }
    else
    {
        //这里不太完善,有待改进
        for(e = this->table + i,e=e->next; e!=NULL; e=e->next)
        {
            if((e->hash == hashCode) && e->key == k)
            {
                void *oldValue = e->value; //取原来的旧的值
                e->value = v; //设置新值
 
                return oldValue; //返回旧值
            }
        }
    }
 
    //新的
    addEntry(this,k,v,hashCode,i);
    return NULL;
}
 
 
//返回指定键在此标识哈希映射中所映射的值,如果对于此键来说,映射不包含任何映射关系,则返回 null。
void *hashmap_get(HashMap this,void *k)
{
    int hashCode;
 
    if(this->K_E == E_STRING)
    {
        hashCode = hash(stringHashCode(k));
    }
    else if(this->K_E == E_INT)
    {
        hashCode = hash(k);
    }
    else
    {
        hashCode = hash(k);
    }
 
    int i = indexFor(hashCode,this->capacity);
    Entry e;
 
    if(this->K_E == E_STRING || this->K_E == E_INT)
    {
        for(e=this->table + i,e=e->next; e!=NULL; e=e->next)
        {
            if(e->hash == hashCode && (e->key == k || strcmp(e->key,k) == 0))
            {
                return e->value;
            }
        }
 
        return NULL;
    }
    else
    {
        //这里不太完善,有待改进
        for(e=this->table + i,e=e->next; e!=NULL; e=e->next)
        {
            if(e->hash == hashCode && e->key == k)
            {
                return e->value;
            }
        }
 
        return NULL;
    }
 
    return NULL;
 
}
 
 
//如果此映射中存在该键的映射关系,则将其删除。
//注意在返回处理完成后,free();
void *hashmap_remove(HashMap this,void *k)
{
    int hashCode;
 
    if(this->K_E == E_STRING)
    {
        hashCode = hash(stringHashCode(k));
    }
    else if(this->K_E == E_INT)
    {
        hashCode = hash(k);
    }
    else
    {
        hashCode = hash(k);
    }
 
    int i = indexFor(hashCode,this->capacity);
    Entry e;
    Entry preE=NULL; //上一个
 
    for(e=this->table+i,preE=e,e=e->next; e!=NULL; preE=e,e=e->next)
    {
        if(e->hash == hashCode && (e->key == k || strcmp(e->key,k) == 0))
        {
            if(e->next == NULL)
            {
                preE->next = NULL;
            }
            else
            {
                preE->next = e->next;  //将此结点删除
            }
 
            e->next = NULL; //设置为NULL
 
            this->size--; //size - 1
 
            //free(e); //这里释放内存后,为什么下面还能正常返回值?
 
            return e->value;
        }
    }
 
    return NULL;
}
 
//返回此映射中所包含的键的 set 视图
//注意在返回处理完成后,free();
HashMapSet hashmap_keySet(HashMap this)
{
    int size = this->size;
 
    if(size == 0)
    {
        return NULL;
    }
    else
    {
        HashMapSet set = malloc(sizeof(struct _hashmapset));
        set->key = NULL;
        set->next = NULL;
 
        int i;
        Entry e;
        HashMapSet preSet = set; //上一个Set
 
        int capacity = this->capacity;
        for(i=0; i<capacity; i++)
        {
            for(e = this->table + i,e=e->next; e!=NULL; e=e->next)
            {
                if(preSet->key == NULL)
                {
                    //第一次赋值
                    preSet->key = e->key;
                    preSet->next = NULL;
                }
                else
                {
                    //添加一个新结点
                    HashMapSet item = malloc(sizeof(struct _hashmapset));
                    item->key = e->key;
                    item->next = NULL;
 
                    preSet->next = item;
 
                    preSet = item; //
                }
            }
        }
 
        return set;
    }
}
 
 
//从此映射中移除所有映射关系。
void hashmap_clear(HashMap this)
{
    int capacity = this->capacity;
    int i;
    Entry e,item;
    for(i=0; i<capacity; i++)
    {
        for(e = this->table + i,e=e->next; e!=NULL; item = e,e=e->next,free(item))
        {
        }
 
        (this->table + i)->next = NULL; //重置为NULL
    }
 
    //free(this->table);
 
    this->size = 0;
}
 
 
//释放内存
void hashmap_free(HashMap this)
{
    int capacity = this->capacity;
    Entry e,item;
    int i;
    for(i=0; i<capacity; i++)
    {
        for(e=this->table + i, e=e->next; e!=NULL; item=e,e=e->next,free(item))
        {
        }
    }
 
    this->capacity = 0;
    this->size = 0;
 
    free(this->table);
    free(this);
}
关注
test_lockxxx
test_lockxxx
等级:
#2 得分:0回复于: 2012-05-04 06:19:59
测试hashmap用的例子:

main.c

C/C++ code

 

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hashmap.h"
 
typedef struct object
{
    char *name;
    int age;
} *Object;
 
int main()
{
    //初始化
    HashMap map = hashmap_init(E_STRING,E_INT);
 
    //检查hash碰撞,比如 'rQ' 和 'qp' 的 hashcode 一样
    hashmap_put(map,"rQ",1);
    hashmap_put(map,"qp",2);
 
    hashmap_put(map,"a1",1);
    hashmap_put(map,"a2",2);
    hashmap_put(map,"a3",3);
 
    hashmap_put(map,"b1",1);
    hashmap_put(map,"b2",2);
    hashmap_put(map,"b3",3);
    hashmap_put(map,"b4",4);
    hashmap_put(map,"b5",5);
    hashmap_put(map,"b6",6);
    hashmap_put(map,"b7",7);
    hashmap_put(map,"b8",8);
    hashmap_put(map,"b9",9);
 
    char *p = malloc(sizeof(char) * 10);
    strcpy(p,"a1");
    hashmap_put(map,p,1);
 
    hashmap_put(map,"rQrQ",5);
    hashmap_put(map,"rQqp",6);
    hashmap_put(map,"qprQ",7);
    hashmap_put(map,"qpqp",8);
 
    hashmap_put(map,"你1好",11);
    hashmap_put(map,"你2好",12);
    hashmap_put(map,"你3好",13);
 
 
    printf("----------------------------put\n");
    printf("put(rQqp):%d\n",hashmap_put(map,"rQqp",60));
    printf("put(qprQ):%d\n",hashmap_put(map,"qprQ",60));
 
 
    printf("----------------------------get\n");
    char *t = malloc(sizeof(char) * 10);
    strcpy(t,"a1");
    printf("get(a1):%d\n",hashmap_get(map,t));
 
    printf("get(rQqp):%d\n",hashmap_get(map,"rQqp"));
    printf("get(qpqp):%d\n",hashmap_get(map,"qpqp"));
    printf("get(你1好):%d\n",hashmap_get(map,"你1好"));
    printf("get(你2好):%d\n",hashmap_get(map,"你2好"));
    printf("get(你3好):%d\n",hashmap_get(map,"你3好"));
 
 
    printf("----------------------------remove\n");
    printf("remove(你1好):%d\n",hashmap_remove(map,"你1好"));
    printf("remove(qpqp):%d\n",hashmap_remove(map,"qpqp"));
    printf("\n");
    printf("get(rQqp):%d\n",hashmap_get(map,"rQqp"));
    printf("get(qpqp):%d\n",hashmap_get(map,"qpqp"));
    printf("get(你1好):%d\n",hashmap_get(map,"你1好"));
    printf("get(你2好):%d\n",hashmap_get(map,"你2好"));
    printf("get(你3好):%d\n",hashmap_get(map,"你3好"));
 
    printf("----------------------------keySet\n");
    printf("size:%d\n",map->size);
 
    HashMapSet set;
    for(set = hashmap_keySet(map); set!=NULL; set=set->next)
    {
        printf("%s:%d\n",set->key,hashmap_get(map,set->key));
    }
 
    printf("----------------------------clear\n");
    hashmap_clear(map);
    printf("size:%d\n",map->size);
 
    //HashMapSet set;
    for(set = hashmap_keySet(map); set!=NULL; set=set->next)
    {
        printf("%s:%d\n",set->key,hashmap_get(map,set->key));
    }
 
 
    return 0;
}
关注
qq120848369 
qq120848369
等级:
8
9
6
#3 得分:10回复于: 2012-05-04 16:13:01
感谢分享.
关注
lbq199204
lbq199204
等级:
#4 得分:10回复于: 2012-05-04 19:06:12
刚学完c(谭浩强版那本书),正学java中的白菜,看到Lz如此,我觉得,我连c的皮毛都没学到。帮忙顶了,感谢LZ分享,但是,我以后也会写出这般代码的!鼓励自己一下。哈,谢谢lz分享。
关注
test_lockxxx
test_lockxxx
等级:
#5 得分:0回复于: 2012-05-05 05:40:50
今天早上测试 hashmap的key = 0(NULL)的时候,发现hashmap_keySet()函数有一个问题:

修改后的hashmap_keySet()如下:

C/C++ code

 

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//返回此映射中所包含的键的 set 视图
//注意在调用该函数的代码段中,处理完HashMapSet后,要free(HashMapSet);
HashMapSet hashmap_keySet(HashMap this)
{
    //head 结点
    HashMapSet set = malloc(sizeof(struct _hashmapset));
    set->key = NULL;
    set->next = NULL;
 
    int i;
    Entry e;
    HashMapSet preSet = set; //上一个Set
 
    int capacity = this->capacity;
    for(i=0; i<capacity; i++)
    {
        for(e = this->table + i,e=e->next; e!=NULL; e=e->next)
        {
            //添加一个新结点
            HashMapSet item = malloc(sizeof(struct _hashmapset));
            item->key = e->key;
            item->next = NULL;
 
            preSet->next = item;
 
            preSet = item; //
        }
    }
 
    return set->next;
}

m2014-c->c模拟java的hashmap容器类的更多相关文章

  1. Java中HashMap的实现原理

    最近面试中被问及Java中HashMap的原理,瞬间无言以对,因此痛定思痛觉得研究一番. 一.Java中的hashCode和equals 1.关于hashCode hashCode的存在主要是用于查找 ...

  2. Java中的容器类(List,Set,Map,Queue)

    Java中的容器类(List,Set,Map,Queue) 一.基本概念 Java容器类类库的用途是“保存对象”,并将其划分为两个不同的概念: 1)Collection.一个独立元素的序列,这些元素都 ...

  3. Java:HashMap的实现原理(JDK1.8)

    1.    HashMap概述: HashMap是基于哈希表的Map接口的非同步实现.此实现提供所有可选的映射操作,并允许使用null值和null键.此类不保证映射的顺序,特别是它不保证该顺序恒久不变 ...

  4. [转]java 的HashMap底层数据结构

    java 的HashMap底层数据结构   HashMap也是我们使用非常多的Collection,它是基于哈希表的 Map 接口的实现,以key-value的形式存在.在HashMap中,key-v ...

  5. java:警告:[unchecked] 对作为普通类型 java.util.HashMap 的成员的put(K,V) 的调用未经检查

    java:警告:[unchecked] 对作为普通类型 java.util.HashMap 的成员的put(K,V) 的调用未经检查 一.问题:学习HashMap时候,我做了这样一个程序: impor ...

  6. angularJS操作键值对象(类似java的hashmap)填坑小结

    前言: 我们知道java的hashmap中使用最多的是put(...),get(...)以及remove()方法,那么在angularJS中如何创造(使用)这样一个对象呢 思路分析: 我们知道在jav ...

  7. Java学习——HashMap

    遍历 Map map = new HashMap(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map. ...

  8. 模拟java.util.Collection一些简单的用法

    /* 需求:模拟java.util.Collection一些简单的用法! 注意:java虚拟机中并没有泛型类型的对象.泛型是通过编译器执行一个被称为类型擦除的前段转换来实现的. 1)用泛型的原生类型替 ...

  9. Java之HashMap在多线程情况下导致死循环的问题

    PS:不得不说Java编程思想这本书是真心强大.. 学习内容: 1.HashMap<K,V>在多线程的情况下出现的死循环现象   当初学Java的时候只是知道HashMap<K,V& ...

随机推荐

  1. 简单hello world

    第一步配置路由: 打开app/http/route.php文件,输入:Route::get('/home', 'HomeController@index'); 第二步配置控制器: 控制文件可以手动添加 ...

  2. EF4.1 企业架构模式 自动映射数据表(转载)

    在讲解之前,先来看看解决方案的架构: 1.在Nop.Core下的Domain里建立一个实体Category:2.在Nop.Data下的Mapping\Catatog\下建立一个数据表映射Categor ...

  3. 自己的一个验证电话和ecshop验证电话

    //验证电话 function checkPhone($phone) { $preg_mobile = preg_match("/^1\d{10}$/", $phone ); $p ...

  4. tbnet编译

    下载tbnet 下载地址:http://code.taobao.org/p/tb-common-utils/src/trunk/tbnet/ ,它的svn地址为:http://code.taobao. ...

  5. nexus 配置

    1.下载 http://www.sonatype.org/nexus/go/  例如:nexus-2.11.4-01-bundle.tar.gz 2.解压 tar -xzvf nexus-2.11.4 ...

  6. [Jobdu] 题目1507:不用加减乘除做加法

    题目描述: 写一个函数,求两个整数之和,要求在函数体内不得使用+.-.*./四则运算符号. 输入: 输入可能包含多个测试样例.对于每个测试案例,输入为两个整数m和n(1<=m,n<=100 ...

  7. 关于搭配junit 和JUnit报initializationError的解决方法

    关于junit是什么就不复述了,网上有 junit的source code是可以下载的,各个版本都有 地址:https://github.com/junit-team 通过junit 的source ...

  8. 16位结构的CPU,8086给出物理地址的方法

    .16位结构的CPU 概括地讲,16位结构(16位机,字长为16位等常见说法,与16位结构的含义相同)描述了一个CPU具有下面几方面结构特性: 1.运算器一次最多可以处理16位的数据结构 2.寄存器的 ...

  9. Unix系统编程()复制文件描述符

    Bourne shell的IO重定向语法2>&1,意在通知shell把标准错误(文件描述符2)重定向到标准输出(文件描述符1).因此下列命令将把标准输出和标准错误写入result.log ...

  10. ngx_lua模块学习示例之waf

    转自:http://www.tuicool.com/articles/FbQ3ymB WAF的主要功能为: ip黑白名单 url黑白名单 useragent黑白名单 referer黑白名单 常见web ...