Java(1.8)集合类中的HashMap

来源:互联网 发布:js indexof 第二个 编辑:程序博客网 时间:2024/05/20 20:43

Java(1.8)集合类中的HashMap
Java(1.8) 集合中的LinkedList
Java(1.8) 集合中的ArrayList

Map接口没有继承任何其他接口,它存储的是Key-Value对,并且Key不能重复。
下面就是Map的所有接口:

Map接口的所有方法
HashMap 内部每个Key-Value对都用一个Node对象存储。在Node中保持了key的hash值,Key,Value,和指向下个Node的next变量。

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内还有个内部类叫TreeNode,这个其实继承了Node类。这个类用作红黑树的节点。

TreeNode

HashMap用一个数组来保存元素的,每个数组的的数据可以是一个Node组成的链表,或者是TreeNode组成的红黑树。

transient Node<K,V>[] table;

在内部还有个重要的变量entrySet, 这个Set对象的用处就是当调用map.keySet()和values()方法时,通过这个entrySet来遍历所有的元素。

transient Set<Map.Entry<K,V>> entrySet;

看下put(K key, V value)的实现

  public V put(K key, V value) {        return putVal(hash(key), key, value, false, true);    }

先把key做个Hash计算,如果hashCode 的值小于2的16次方的时候, hash值就是key.hashCode()的值,如果大于,会把高低位进行异或计算。

 static final int hash(Object key) {        int h;        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);    }

再看方法:putVal,如果第一次添加,就会初始化一个默认16长度的数组(这个逻辑在resize()里面)
添加元素的逻辑:
- 如果在数组找不到hash对应的元素,就会new一个新的Node并放入table数组相应位置中。
- 如果数组的里的元素的key 和要插入的key 一直,就把当前value更新
- 如果查到的元素是个TreeNode类型的,1)如果存在更新value,2)如果不存在,new个新的TreeNode,然后插入的树中。
- 如果是个链表类型,1)如果存在更新value,2)如果不存在,new个新的Node,然后插入链表中。

 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,                   boolean evict) {        Node<K,V>[] tab; Node<K,V> p; int n, i;        if ((tab = table) == null || (n = tab.length) == 0)            n = (tab = resize()).length;        if ((p = tab[i = (n - 1) & hash]) == null)            tab[i] = newNode(hash, key, value, null);        else {            Node<K,V> e; K k;            if (p.hash == hash &&                ((k = p.key) == key || (key != null && key.equals(k))))                e = p;            else if (p instanceof TreeNode)                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);            else {                for (int binCount = 0; ; ++binCount) {                    if ((e = p.next) == null) {                        p.next = newNode(hash, key, value, null);                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st                            treeifyBin(tab, hash);                        break;                    }                    if (e.hash == hash &&                        ((k = e.key) == key || (key != null && key.equals(k))))                        break;                    p = e;                }            }            if (e != null) { // existing mapping for key                V oldValue = e.value;                if (!onlyIfAbsent || oldValue == null)                    e.value = value;                afterNodeAccess(e);                return oldValue;            }        }        ++modCount;        if (++size > threshold)            resize();        afterNodeInsertion(evict);        return null;    }

再看resize()方法,:
- 首次初始化,数组长度默认是16
- 如果table已经有元素了,并且当前数组长度的2倍小于最大容量,就把数组扩容到以前的2倍,有了新数组,就把老数据拷贝到新数组。
- HashMap里面有个threshold,这个值总比数组的size小,初始化的时候,默认为threshold=16*0.75=12,当HashMap的size大于threshold的时候就要扩容,并非table已经满了。下次扩容的时候,threshold的大小当前threshold的2倍。

 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;    }
原创粉丝点击