HashMap 小解

HashMap 实现原理
1.HashMap概述
HashMap是基于哈希表的MAP接口的非同步实现,此实现提供所有可选的映射操作,并允许使用null作为key或value的值。
这个类不保证映射的顺序,特别是它不保证顺序恒久不变

2.HashMap的数据机构
 HashMap底层就是一个数组,数组的每一项又是一个链表。数组+链表

 水平的表示数组,垂直的表示链表

 


--谈谈HashMap的常用方法
3.HashMap默认构造器
  //初始数组长度
  static final int DEFAULT_INITIAL_CAPACITY = 16;
  //负载因子
  static final float DEFAULT_LOAD_FACTOR = 0.75f;
  //实体数组
  transient Entry[] table;
  //允许的最大元素数目 临界值
  int threshold;
  //修改次数
  transient volatile int modCount;
  
  public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
        table = new Entry[DEFAULT_INITIAL_CAPACITY];
        init();
    }

   void init() {
    }
 
 表示的意思很是直白:构建一个初始容量为 16,负载因子为 0.75 的 HashMap。
 
 4.常用的put方法
  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;
//如果hash相同,但key值不同,那么新添加的 怎么办?后面有说明
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
//链表中删除old值,替换新值
                e.recordAccess(this);
                return oldValue;
            }

        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }
  
  //key 为null,直接放在数组的第一个索引处
  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;
    }

//按"与"运算 该对象应该保存在 table 数组的哪个索引处
static int indexFor(int h, int length) {
        return h & (length-1);
    }

//1.计算出的hash值,将key-value对放在数组table的bucketIndex索引处
//2.如果hash相同,但key值不同,那么新添加的 Entry 将与集合中原有 Entry 形成 Entry 链,
//而且新添加的 Entry 位于 Entry 链的头部
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);
    }

//容量的扩展
void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
//达到极限值就没法扩展,直接返回88
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }


        Entry[] newTable = new Entry[newCapacity];
//old的元素更新到扩展后的hashmap中
        transfer(newTable);
        table = newTable;
        threshold = (int)(newCapacity * loadFactor);
    }
 
5.常用的get方法
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;
//查询的时候,不仅仅找找到对应的hash就OK了,还要判断key的哦!
            if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
                return e.value;
        }
        return null;
    }

//查询key为null,直接到数组第一元素处找
private V getForNullKey() {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }

6.常用的remove方法
public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key);
        return (e == null ? null : e.value);
    }

 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--;
//作用就是把将要删除节点的前一个节点next指向删除被删除的节点next
                if (prev == e)  //如果链表就一个元素,那么会执行此处
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
    //重新赋值当前节点
            prev = e;
    //重新赋值下一个节点
            e = next;
        }
        return e;
    }

 先找到table数组中对应的索引,接着就类似于一般的链表的删除操作,而且是单向链表删除节点,将要删除节点的前一节点的next指向删除被删除节点的next即可。


7.看看上面几处源码,你会发现modCount这变量。它是干嘛的?
 Fail-Fast机制:是java集合的一种错误机制。当多个线程对同一个集合内容进行操作是,就可能产生fail-fast事件。
 场景:当某一个线程A通过Iiteator去遍历某集合过程中,若该集合的内容被其他线程所改变了;那么线程A访问集合时,
  就会抛出ConcurrentModificationException异常,产生fail-fast事件。
  
  HashMap是线程不安全的,因此会出现这种场景,HashMap是通过modCount判断是否要抛出此异常。对HashMap的内容的修改都将增加这个值,
  那么在迭代器初始过程中会将这个值赋给迭代的expectedModCount。
   HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }
 
   在迭代的过程判断modCount和expectedModCount是否相等,不等就抛出ConcurrentModificationException
    final Entry<K,V> nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();


            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
   current = e;
            return e;
        }


注:
transient是类型修饰符,只能用来修饰字段。在对象序列化的过程中,标记为transient的变量不会被序列化
modCount声明为volatile,保证线程之间修改的可见性。
volatile也是变量修饰符,只能用来修饰变量。volatile修饰的成员变量在每次被线程访问时,都强迫从共享内存中重读该成员变量的值。
而且,当成员变量发生变化时,强迫线程将变化值回写到共享内存。这样在任何时刻,两个不同的线程总是看到某个成员变量的同一个值。

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值