Java HashMap的数据结构以及put和get方法

来源:互联网 发布:win7怎么装sqlserver 编辑:程序博客网 时间:2024/06/10 04:34

1 HashMap的数据结构

HashMap实际上是一个链表数组,也就是最外层是数组,数组的元素是链表。

  

2 HashMap的put方法:

源代码如下: 

<span style="font-size:10px;">    public V put(K key, V value) {        //1 如果Key为Null 则put到Key为null的位置        if (key == null)            return putForNullKey(value);        //2 计算Key的hash值        int hash = hash(key.hashCode());        //3 获取index位置        int i = indexFor(hash, table.length);        //4 遍历index位置的链表,如果存在则覆盖并返回旧值,如果不存在就创建一个新位置插入        for (Entry<K,V> e = table[i]; e != null; e = e.next) {            Object k;            //4.1 Key的位置已经有旧的值了 则把新值给旧值 并返回旧值            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {                V oldValue = e.value;                e.value = value;                e.recordAccess(this);                                return oldValue;            }        }        //4.2 如果Key是新的则调用addEntry插入新的Key和value        modCount++;        addEntry(hash, key, value, i);        return null;    }</span>

 

3 源代码如下HashMap的get方法:

源代码如下: 

<span style="font-size:10px;">    public V get(Object key) {        //1 如果Key是null 直接返回key为null位置的值        if (key == null)            return getForNullKey();        //2 计算Key对象的hash值        int hash = hash(key.hashCode());        for (Entry<K,V> e = table[indexFor(hash, table.length)]; //通过计算Key的hash找到index             e != null;             e = e.next) {//在index中找遍历链表            Object k;            //通过equals比较找到Key位置 如果找到Key 并返回value            if (e.hash == hash && ((k = e.key) == key || key.equals(k)))                return e.value;        }        return null;    }</span>


4 concurrentHashMap的分析:

主要是划分segment

 

参考资料:

java提高篇(二三)-----HashMap

源码分析之ConcurrentHashMap

 

0 0