java提高篇—hashMap的底层原理(01)

来源:互联网 发布:mac安装什么杀毒软件 编辑:程序博客网 时间:2024/06/05 20:24

hashMap的理解

1.hashMap有key-value

2.底层原理是以数组和链表进行实现(如图1)

(图1,来自百度百科)


3.图2是我根据我写的代码化的一个抽象图

(图2)


4.以上图可见,首先必须得创建一个为Entry的类

/** * 创建Entry类, */public class Entry<V> {    private V key;    private V value;    Entry(V key,V value){       this.value = value;        this.key = key;    }    public Object getKey() {        return key;    }    public void setKey(V key) {        this.key = key;    }    public V getValue() {        return value;    }    public void setValue(V value) {        this.value = value;    }}

5,创建我的MyHashMap

import java.util.LinkedList;/** * 代码演示以明白算法和实现原理为主 */public class MyHashMap {    LinkedList[] linkedLists = new LinkedList[999];    //添加数据    public void put(Object key,Object value){        Entry e = new Entry(key,value);        //具体算法有很多种,我用的是以key的hash值%数组的长度        //算出的a,就是数据在数组中的角标        int a = (key.hashCode()% linkedLists.length);        //看LinkedList[a]是否有数据        if(linkedLists[a] == null){            LinkedList list = new LinkedList();            list.add(e);            linkedLists[a]=list;        }else{            //如果有数据,按照hashMap,需判断key值            LinkedList list = linkedLists[a];            for(int i=0;i<list.size();i++){                Entry entry = (Entry) list.get(i);                //如果key值相同,则覆盖value值                if(entry.getKey().equals( key)){                    entry.setValue(value);                    return;                }            }            list.add(e);        }    }    public Object get(Object key){        //取出的算法和放入数据的算法必须一致        int a =(key.hashCode()%linkedLists.length);        if(linkedLists[a] == null){            return null;        }else{            LinkedList list = linkedLists[a];            for(int i=0;i<list.size();i++){                Entry entry = (Entry) list.get(i);                if(entry.getKey().equals( key)){                    return entry.getValue();                }            }            return null;        }    }}
6.运行结果如下


0 0
原创粉丝点击