HashMap和Hashtable的底层实现都是数组+链表结构实现的,这点上完全一致

添加、删除、获取元素时都是先计算hash,根据hash和table.length计算index也就是table数组的下标,然后进行相应操作,下面以HashMap为例说明下它的简单实现

  /**
* HashMap的默认初始容量 必须为2的n次幂
*/
static final int DEFAULT_INITIAL_CAPACITY = 16; /**
* HashMap的最大容量,可以认为是int的最大值
*/
static final int MAXIMUM_CAPACITY = 1 << 30; /**
* 默认的加载因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f; /**
* HashMap用来存储数据的数组
*/
transient Entry[] table;
  • HashMap的创建
    HashMap默认初始化时会创建一个默认容量为16的Entry数组,默认加载因子为0.75,同时设置临界值为16*0.75

        /**
    * Constructs an empty <tt>HashMap</tt> with the default initial capacity
    * (16) and the default load factor (0.75).
    */
    public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
    table = new Entry[DEFAULT_INITIAL_CAPACITY];
    init();
    }
  • put方法
    HashMap会对null值key进行特殊处理,总是放到table[0]位置
    put过程是先计算hash然后通过hash与table.length取摸计算index值,然后将key放到table[index]位置,当table[index]已存在其它元素时,会在table[index]位置形成一个链表,将新添加的元素放在table[index],原来的元素通过Entry的next进行链接,这样以链表形式解决hash冲突问题,当元素数量达到临界值(capactiy*factor)时,则进行扩容,是table数组长度变为table.length*2
  •  public V put(K key, V value) {
    if (key == null)
    return putForNullKey(value); //处理null值
    int hash = hash(key.hashCode());//计算hash
    int i = indexFor(hash, table.length);//计算在数组中的存储位置
    //遍历table[i]位置的链表,查找相同的key,若找到则使用新的value替换掉原来的oldValue并返回oldValue
    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;
    }
    }
    //若没有在table[i]位置找到相同的key,则添加key到table[i]位置,新的元素总是在table[i]位置的第一个元素,原来的元素后移
    modCount++;
    addEntry(hash, key, value, i);
    return null;
    } void addEntry(int hash, K key, V value, int bucketIndex) {
    //添加key到table[bucketIndex]位置,新的元素总是在table[bucketIndex]的第一个元素,原来的元素后移
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
    //判断元素个数是否达到了临界值,若已达到临界值则扩容,table长度翻倍
    if (size++ >= threshold)
    resize(2 * table.length);
    }
  • get方法
    同样当key为null时会进行特殊处理,在table[0]的链表上查找key为null的元素
    get的过程是先计算hash然后通过hash与table.length取摸计算index值,然后遍历table[index]上的链表,直到找到key,然后返回
    public V get(Object key) {
    if (key == null)
    return getForNullKey();//处理null值
    int hash = hash(key.hashCode());//计算hash
    //在table[index]遍历查找key,若找到则返回value,找不到返回null
    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;
    }
  • remove方法
    remove方法和put get类似,计算hash,计算index,然后遍历查找,将找到的元素从table[index]链表移除
        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--;
    if (prev == e)
    table[i] = next;
    else
    prev.next = next;
    e.recordRemoval(this);
    return e;
    }
    prev = e;
    e = next;
    } return e;
    }
  • resize方法
    resize方法在hashmap中并没有公开,这个方法实现了非常重要的hashmap扩容,具体过程为:先创建一个容量为table.length*2的新table,修改临界值,然后把table里面元素计算hash值并使用hash与table.length*2重新计算index放入到新的table里面
    这里需要注意下是用每个元素的hash全部重新计算index,而不是简单的把原table对应index位置元素简单的移动到新table对应位置
    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);
    } 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;
    //重新对每个元素计算index
    int i = indexFor(e.hash, newCapacity);
    e.next = newTable[i];
    newTable[i] = e;
    e = next;
    } while (e != null);
    }
    }
    }
  • clear()方法
    clear方法非常简单,就是遍历table然后把每个位置置为null,同时修改元素个数为0
    需要注意的是clear方法只会清楚里面的元素,并不会重置capactiy
     public void clear() {
    modCount++;
    Entry[] tab = table;
    for (int i = 0; i < tab.length; i++)
    tab[i] = null;
    size = 0;
    }
  • containsKey和containsValue
    containsKey方法是先计算hash然后使用hash和table.length取摸得到index值,遍历table[index]元素查找是否包含key相同的值
    public boolean containsKey(Object key) {
    return getEntry(key) != null;
    }
    final Entry<K,V> getEntry(Object key) {
    int hash = (key == null) ? 0 : 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 != null && key.equals(k))))
    return e;
    }
    return null;
    }

    containsValue方法就比较粗暴了,就是直接遍历所有元素直到找到value,由此可见HashMap的containsValue方法本质上和普通数组和list的contains方法没什么区别,你别指望它会像containsKey那么高效

    public boolean containsValue(Object value) {
    if (value == null)
    return containsNullValue(); Entry[] tab = table;
    for (int i = 0; i < tab.length ; i++)
    for (Entry e = tab[i] ; e != null ; e = e.next)
    if (value.equals(e.value))
    return true;
    return false;
    }
  • hash和indexFor
    indexFor中的h & (length-1)就相当于h%length,用于计算index也就是在table数组中的下标
    hash方法是对hashcode进行二次散列,以获得更好的散列值
    为了更好理解这里我们可以把这两个方法简化为 int index= key.hashCode()/table.length,以put中的方法为例可以这样替换
    int hash = hash(key.hashCode());//计算hash
    int i = indexFor(hash, table.length);//计算在数组中的存储位置
    //上面这两行可以这样简化
    int i = key.key.hashCode()%table.length;
  •   static int hash(int h) {
    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
    } static int indexFor(int h, int length) {
    return h & (length-1);
    }

HashMap和Hashtable的实现原理的更多相关文章

  1. HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别

    ①HashMap的工作原理 HashMap基于hashing原理,我们通过put()和get()方法储存和获取对象.当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算h ...

  2. (转)HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别

    ①HashMap的工作原理 HashMap基于hashing原理,我们通过put()和get()方法储存和获取对象.当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算h ...

  3. HashMap,Hashtable,ConcurrentHashMap 和 synchronized Map 的原理和区别

    HashMap 是否是线程安全的,如何在线程安全的前提下使用 HashMap,其实也就是HashMap,Hashtable,ConcurrentHashMap 和 synchronized Map 的 ...

  4. HashMap底层实现原理以及HashMap与HashTable区别以及HashMap与HashSet区别

    ①HashMap的工作原理 HashMap基于hashing原理,我们通过put()和get()方法储存和获取对象.当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算h ...

  5. HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别(转)

    HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别 文章来源:http://www.cnblogs.com/beatIteWeNerverGiveU ...

  6. HashMap与HashTable原理及数据结构

    HashMap与HashTable原理及数据结构 hash表结构个人理解 hash表结构,以计算出的hashcode或者在hashcode基础上加工一个hash值,再通过一个散列算法 获取到对应的数组 ...

  7. Hashmap与Hashtable的区别及Hashmap的原理

    Hashtable和HashMap有几个主要的不同:线程安全以及速度.仅在你需要完全的线程安全的时候使用Hashtable,而如果你使用Java 5或以上的话,请使用ConcurrentHashMap ...

  8. [转帖]HashMap、HashTable、ConcurrentHashMap的原理与区别

    HashMap.HashTable.ConcurrentHashMap的原理与区别 http://www.yuanrengu.com/index.php/2017-01-17.html 2017年1月 ...

  9. HashMap,HashTable,ConcurrentHashMap的实现原理及区别

    http://youzhixueyuan.com/concurrenthashmap.html 一.哈希表 哈希表就是一种以 键-值(key-indexed) 存储数据的结构,我们只要输入待查找的值即 ...

随机推荐

  1. Linq 左连接 left join

    Suppose you have a tblRoom and tblUserInfo. Now, you need to select all the rooms regardless of whet ...

  2. android 多点触控

    多点触控 1.多点触控从字面意思讲就是你用大于等于2根的手指触摸子啊手机屏幕上. Android中监听触摸事件是onTouchEvent方法,它的参数为MotionEvent,下面列举MotionEv ...

  3. SQL SERVER2008 R2修改Server Collation--文檔沒細看先存下來.

    HOW TO: RESTORE THE MASTER DATABASE IN SQL SERVER 2012 by Thomas LaRock | Jan 14, 2014 | MSSQL, SQL ...

  4. angular 输入属性

    import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-order', templa ...

  5. 「HAOI2016」放棋子

    题目链接 戳这 前置知识 错位排序 Solution 我们可以观察发现,每一行的障碍位置对答案并没有影响. 于是我们可以将此时的矩阵化成如下形式: \[ 1\ \ 0\ \ 0\ \ 0\\ 0\ \ ...

  6. F题(水题)

    给出一个有N个数的序列,编号0 - N - 1.进行Q次查询,查询编号i至j的所有数中,最大的数是多少.   例如: 1 7 6 3 1.i = 1, j = 3,对应的数为7 6 3,最大的数为7. ...

  7. 数据结构之BF算法,kmp算法,三元组,十字链表总结

    在这一章中,老师教了我们四种数据结构:BF算法,kmp算法,三元组和十字链表:还给我们讲了2019年团体天体赛中T1-8的AI题 1.对于BF和kmp算法,老师除了在课堂上讲解算法的主要核心思想外,还 ...

  8. 连续bezier曲线的实现

    需求场景 一系列的坐标点,划出一条平滑的曲线 3次Bezier曲线 基本上大部分绘图工具都实现了3次Bezier曲线,4个点确定一条3次Bezier曲线.以html5中的canvas为例 let ct ...

  9. ASPxGridView后台实现隐藏新增按钮

    (ASPxGridView2.Columns[0] as GridViewCommandColumn).NewButton.Visible = false;//0应该代表的是NewButton所在的列 ...

  10. 决策树--Python

    决策树 实验集数据: #coding:utf8 #关键词:决策树(desision tree).特征选择.信息增益(information gain).香农熵.熵(entropy).经验熵(H(D)) ...