JAVA容器-浅谈HashMap的实现原理

概述

  HashMap是通过数组+链表的方式实现的,由于HashMap的链表也是采用数组方式,我就修改直接利用LinkedList实现,简单模拟一下。

  1、Key、Value的存取方式。

  2、HashMap与HashTable的区别

    HashMap线程不安全、K、V可以为空,效率较高,没有contains方法。

    HashTable线程安全,K、V不能为空,效率较低。

  3、简述hash的实现原理

模拟实现

1、综述实现原理

(1)建立一个数组用于存储链表的引用,然后链表里面存储的内容为Entry(包含key、value)。

(2)获得对象的hashCode,利用哈希散列表的方式,分布在数组里面。

(3)当我们存对象的时候,我们只需要获得key、value。根据key的hash,找到列表的位置。遍历链表,若key存在覆盖,否则添加。

(4)重点:对象的hashCode就是链表在数组的引用位置。

2、若搞清楚上述问题,就不难了。

 1 public class MyHashMap {
 2     //HashMap实现:数组+链表
 3     private LinkedList<Entry> [] arrys=new LinkedList[999];
 4     public void put(Object key,Object value){
 5         //获得对象的hashCode
 6         int tempInteger=key.hashCode()%999;
 7         int hash=tempInteger<0?-tempInteger:tempInteger;
 8         //若链表为空,则新建链表
 9         if(null==arrys[hash]){
10             LinkedList<Entry> ls=new LinkedList<Entry>();
11             Entry e=new Entry();
12             e.key=key;
13             e.value=value;
14             ls.add(e);
15             arrys[hash]=ls;
16         }else{
17             //若链表不为空,遍历链表看是否有重复key值。
18             LinkedList<Entry> ls=arrys[hash];
19             for(Entry e:ls){
20               if((key).equals(e.key)){
21                   e.value=value;
22                   return;
23               }
24             }
25             ls.add(new Entry(key,value));
26         }
27     }
28 
29     //根据key值获得对象
30     public Object get(Object key){
31         int hash=key.hashCode()%999;
32         LinkedList<Entry> ls=arrys[hash];
33         if(null!=ls){
34             for(Entry e:ls){
35                 if((key).equals(e.key)){
36                     return e.value;
37                 }
38             }
39         }
40         return null;
41     }
42 
43     //条目
44     class Entry{
45         Object key;
46         Object value;
47         public Entry() {}
48 
49         public Entry(Object key, Object value) {
50             this.key = key;
51             this.value = value;
52         }
53     }
54 }
posted @ 2017-03-16 20:06  码农皮邱  阅读(471)  评论(0编辑  收藏  举报