HashMap的进一步理解

1. 数据结构
Java代码  收藏代码
transient Entry[] table;  
用数组和链表来实现,实质是链表数组,更进一步说是散列链表数组,因为每一个链表的散列值相同,即Entry的数组,链表和数组的区别见:
[这里写链接内容](http://blog.csdn.net/qq_32215549/article/details/78693679 "链表和数组原理")
![链表图](http://dl2.iteye.com/upload/attachment/0096/9138/f8f48e8c-e09e-36ab-b862-b201ef4a047a.jpg)
Entry(Key,value,next)

 2. Entry链表
实际上HashMap存放的对象是Entry对象,Entry相当于HashMap中的实体,Entry有key,value,hash,next属性,key和value都保存在Entry里
Java代码  收藏代码
final K key;  
V value;  
Entry<K,V> next;  
final int hash;  
 3. 插入元素数据
Java代码  收藏代码
public V put(K key, V value) {  
        if (key == null)  
            return putForNullKey(value);  
        int hash = hash(key.hashCode());  
        int i = indexFor(hash, table.length);  
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {  
            Object k;  
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {  
                V oldValue = e.value;  
                e.value = value;  
                e.recordAccess(this);  
                return oldValue;  
            }  
        }  

        modCount++;  
        addEntry(hash, key, value, i);  
        return null;  
    }  
 代码解读:

添加Null键
Java代码  收藏代码
private V putForNullKey(V value) {  
       for (Entry<K,V> e = table[0]; e != null; e = e.next) {  
           if (e.key == null) {  
               V oldValue = e.value;  
               e.value = value;  
               e.recordAccess(this);  
               return oldValue;  
           }  
       }  
       modCount++;  
       addEntry(0, null, value, 0);  
       return null;  
}  
 在put()方法中,如果key是null,就放在数组的第一个位置上。
  hash()方法(哈希算法)
Java代码  收藏代码
static int hash(int h) {  
        h ^= (h >>> 20) ^ (h >>> 12);  
        return h ^ (h >>> 7) ^ (h >>> 4);  
}  
 这个方法是散列方法(哈希算法),目的是为了生成分布比较均匀的哈希码,进一步了解见
 哈希算法 http://geeksun.iteye.com/blog/513117  和 位移运算 http://geeksun.iteye.com/blog/380032
 indexFor()方法,得出哈希码在Entry数组中的位置
Java代码  收藏代码
static int indexFor(int h, int length) {  
        return h & (length-1);  
}  
 因为是 h & (length-1)返回一个小于length的值,就是在数组中的位置。

 对key相同的Entry的处理:
Java代码  收藏代码
for (Entry<K,V> e = table[i]; e != null; e = e.next) {  
            Object k;  
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {  
                V oldValue = e.value;  
                e.value = value;  
                e.recordAccess(this);  
                return oldValue;  
            }  
}  
 这一段是处理插入相同的key的Entry对象时,把现有value的值更换为新的value值。

插入新Entry数据:
Java代码  收藏代码
void addEntry(int hash, K key, V value, int bucketIndex) {  
    Entry<K,V> e = table[bucketIndex];  
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);  
        if (size++ >= threshold)  
            resize(2 * table.length);  
}  
 如果Entry数组的bucketIndex上已经有Entry存在,就把新的Entry放在bucketIndex位置,原Entry移到新Entry的next指向的位置———在链表头部插入数据,如果bucketIndex位置上没有Entry存在,新插入的Entry的next指向null。
        链表设计——可以看得出这是一个非常优雅的设计。系统总是将新的Entry对象添加到bucketIndex处。如果bucketIndex处已经有了对象,那么新添加的Entry对象将指向原有的Entry对象,形成一条Entry链,但是若bucketIndex处没有Entry对象,也就是e==null,那么新添加的Entry对象指向null,也就不会产生Entry链了。
HashMap使用链表来解决碰撞问题,当两个key的hashcode值一样时,即发生碰撞时,存放在链表的下一个节点中。

 当Entry数组的大小超过阀值时(默认75%),容量扩容一倍。

 Entry数组的扩容(rehash方法)
Java代码  收藏代码
void resize(int newCapacity) {  
       Entry[] oldTable = table;  
       int oldCapacity = oldTable.length;  
       if (oldCapacity == MAXIMUM_CAPACITY) {  
           threshold = Integer.MAX_VALUE;  
           return;  
       }  

       Entry[] newTable = new Entry[newCapacity];  
       transfer(newTable);  
       table = newTable;  
       threshold = (int)(newCapacity * loadFactor);  
}  
 数组扩容时,数组的最大容量是1<<30,当数组的容量为1<<30时,阀点值是Integer的最大值MAX_VALUE。

迁移旧数组的Entry到新数组
Java代码  收藏代码
void transfer(Entry[] newTable) {  
       Entry[] src = table;  
       int newCapacity = newTable.length;  
       for (int j = 0; j < src.length; j++) {  
           Entry<K,V> e = src[j];  
           if (e != null) {  
               src[j] = null;  
               do {  
                   Entry<K,V> next = e.next;  
                   int i = indexFor(e.hash, newCapacity);  
                   e.next = newTable[i];  
                   newTable[i] = e;  
                   e = next;  
               } while (e != null);  
           }  
       }  
}  
       在迁移旧数组的Entry到新数组时,链表的Entry的顺序会反过来,从链表的第一个Entry开始,插入到新链表中,第一个Entry存放到了链尾,最后一个Entry加到了链头,这是为了避免尾部遍历(tail traversing)。
 4. 取出Map中的数据
get()方法:根据Key查找Value
Java代码  收藏代码
public V get(Object key) {  
       if (key == null)  
           return getForNullKey();  
       int hash = hash(key.hashCode());  
       for (Entry<K,V> e = table[indexFor(hash, table.length)];  
            e != null;  
            e = e.next) {  
           Object k;  
           if (e.hash == hash && ((k = e.key) == key || key.equals(k)))  
               return e.value;  
       }  
       return null;  
}  
         查找key对应的value时,先计算出key的散列值,然后遍历散列值对应的Entry链表,如果key的散列值同Entry对象的hash值相等,key和Entry的key值相等,再使用equals()方法比较,如果equals()为true,那么可以确认key是这个Entry对象的key,返回这个Entry对象的value值。
 5.移除HashMap中的指定数据
 移除Entry链表中的对象
Java代码  收藏代码
final Entry<K,V> removeEntryForKey(Object key) {  
        int hash = (key == null) ? 0 : hash(key.hashCode());  
        int i = indexFor(hash, table.length);  
        Entry<K,V> prev = table[i];  
        Entry<K,V> e = prev;  

        while (e != null) {  
            Entry<K,V> next = e.next;  
            Object k;  
            if (e.hash == hash &&  
                ((k = e.key) == key || (key != null && key.equals(k)))) {  
                modCount++;  
                size--;  
                if (prev == e)  
                    table[i] = next;  
                else  
                    prev.next = next;  
                e.recordRemoval(this);  
                return e;  
            }  
            prev = e;  
            e = next;  
        }  

        return e;  
}  
 根据参数key,来移除Entry链表中的key对应的Entry对象,remove()方法中,先计算出key的散列值,再根据散列值找到key对应的Entry所在的bucketIndex位置,然后从bucketIndex位置的Entry链表的头部开始向链尾遍历,如果遍历的Entry对象的hash值与key的hash值相等,Entry对象的key和参数Key的equals()返回true值,就认为找到了key所对应的对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值