Java常用数据结构之HashMap

来源:互联网 发布:虚拟机的网络模式 编辑:程序博客网 时间:2024/05/21 15:50

HashMap的继承结构图:
这里写图片描述

HashMap的底层存储结构

HashMap的底层结构是数组元素为链表的动态数组实现的。
这里写图片描述
底层代码实现

HashMap里几个比较重要的属性

1.默认初始化容量  static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 162.默认最大容量  static final int MAXIMUM_CAPACITY = 1 << 30;3.默认加载因子  static final float DEFAULT_LOAD_FACTOR = 0.75f;4.散列桶中k-v的总数  transient int size;5.重构的阈值(当散列桶中的元素达到该值时将自动扩容)  int threshold; //大小=capacity * load factor6.链表的存储结构  static final Entry<?,?>[] EMPTY_TABLE = {};7.散列桶(数组)   transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;8.与当前对象关联并能减少hash碰撞概率的用于hash(key)的随机种子  transient int hashSeed = 0;
//链表的结点的代码实现static class Node<K,V> implements Map.Entry<K,V> {        final int hash;        final K key;        V value;        Node<K,V> next;        Node(int hash, K key, V value, Node<K,V> next) {            this.hash = hash;            this.key = key;            this.value = value;            this.next = next;        }        public final K getKey()        { return key; }        public final V getValue()      { return value; }        public final String toString() { return key + "=" + value; }        public final int hashCode() {            return Objects.hashCode(key) ^ Objects.hashCode(value);        }        public final V setValue(V newValue) {            V oldValue = value;            value = newValue;            return oldValue;        }        public final boolean equals(Object o) {            if (o == this)                return true;            if (o instanceof Map.Entry) {                Map.Entry<?,?> e = (Map.Entry<?,?>)o;                if (Objects.equals(key, e.getKey()) &&                    Objects.equals(value, e.getValue()))                    return true;            }            return false;        }    }

HashMap的自动扩容

1.当散列桶中元素达到阈值时就进行自动扩容  final Node<K,V>[] resize() {        Node<K,V>[] oldTab = table;        int oldCap = (oldTab == null) ? 0 : oldTab.length;        int oldThr = threshold;        int newCap, newThr = 0;        if (oldCap > 0) {            if (oldCap >= MAXIMUM_CAPACITY) {                threshold = Integer.MAX_VALUE;                return oldTab;            }            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&                     oldCap >= DEFAULT_INITIAL_CAPACITY)                newThr = oldThr << 1; // double threshold        }        else if (oldThr > 0) // initial capacity was placed in threshold            newCap = oldThr;        else {               // zero initial threshold signifies using defaults            newCap = DEFAULT_INITIAL_CAPACITY;            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);        }        if (newThr == 0) {            float ft = (float)newCap * loadFactor;            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?                      (int)ft : Integer.MAX_VALUE);        }        threshold = newThr;        @SuppressWarnings({"rawtypes","unchecked"})            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];        table = newTab;        if (oldTab != null) {            for (int j = 0; j < oldCap; ++j) {                Node<K,V> e;                if ((e = oldTab[j]) != null) {                    oldTab[j] = null;                    if (e.next == null)                        newTab[e.hash & (newCap - 1)] = e;                    else if (e instanceof TreeNode)                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);                    else { // preserve order                        Node<K,V> loHead = null, loTail = null;                        Node<K,V> hiHead = null, hiTail = null;                        Node<K,V> next;                        do {                            next = e.next;                            if ((e.hash & oldCap) == 0) {                                if (loTail == null)                                    loHead = e;                                else                                    loTail.next = e;                                loTail = e;                            }                            else {                                if (hiTail == null)                                    hiHead = e;                                else                                    hiTail.next = e;                                hiTail = e;                            }                        } while ((e = next) != null);                        if (loTail != null) {                            loTail.next = null;                            newTab[j] = loHead;                        }                        if (hiTail != null) {                            hiTail.next = null;                            newTab[j + oldCap] = hiHead;                        }                    }                }            }        }        return newTab;    }2.把old hashMap里的元素进行重散列操作放入new hashMap里  transfer(newTable, initHashSeedAsNeeded(newCapacity));3.重新计算hashSeed  initHashSeedAsNeeded(int capacity) 4.遍历old hashMap里元素重新计算 hash值然后进行存储  hash(Object k) 

HashMap的存储

保证容器里的元素是唯一的

1.先计算hash  int hash = hash(key);2.根据hash值去散列桶中找链表对应得index  int i = indexFor(hash, table.length);3.根据index去遍历链表看是否有相应的对象  for (Entry<K,V> e = table[i]; e != null; e = e.next) 4.如果存在对象就判断old 的hash值与new 的hash是否相等  if(e.hash == hash) {    if(((k = e.key) == key || key.equals(k)))      不做处理    else      添加  }else{    不添加  }