这里讲述的是jdk1.8版本中的HashMap,采用Node数组和链表(或treeNode)的方式实现。

一. HashMap的结构图:

首先有一个Node数组(包含hash,key,value,链表节点),当添加一个元素(key-value)时,就首先计算元素key的hash值,以此确定插入数组中的位置,但是可能存在同一hash值的元素已经被放在数组同一位置了,这时就添加到同一hash值的元素的后面,他们在数组的同一位置,但是形成了链表,同一各链表上的Hash值是相同的,所以说数组存放的是链表。而当链表长度太长时,链表就转换为红黑树,这样大大提高了查找的效率。

二 源码展示

1. HashMap类:

public class HashMap<k,v> extends AbstractMap<k,v> implements Map<k,v>, Cloneable, Serializable {  
      private static final long serialVersionUID =362498820763181265L;  
      static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16  
      static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量  
      static final float DEFAULT_LOAD_FACTOR = 0.75f;//填充比  
      //当add一个元素到某个位桶,其链表长度达到8时将链表转换为红黑树  
      static final int TREEIFY_THRESHOLD = 8;  
      static final int UNTREEIFY_THRESHOLD = 6;  
      static final int MIN_TREEIFY_CAPACITY = 64;  
     transient Node<k,v>[] table;//存储元素的数组  
     transient Set<map.entry<k,v>> entrySet;  
     transient int size;//存放元素的个数  
     transient int modCount;//被修改的次数fast-fail机制  
     int threshold;//临界值 当实际大小(容量*填充比)超过临界值时,会进行扩容   
     final float loadFactor;//填充比

2.4个构造方法:
public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 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; // all other fields defaulted
    }

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

 

 

 Node类:

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;
        }
    }

TreeNode:

1 static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
2         TreeNode<K,V> parent;  // red-black tree links
3         TreeNode<K,V> left;
4         TreeNode<K,V> right;
5         TreeNode<K,V> prev;    // needed to unlink next upon deletion
6         boolean red;
7         TreeNode(int hash, K key, V val, Node<K,V> next) {
8             super(hash, key, val, next);
9         }

 

哈希方法:

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

 

get方法:

public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

获取key的hash值,计算hash&(n-1)得到在链表数组中的位置first=tab[hash&(n-1)],先判断first的key是否与参数key相等,不等就遍历后面的链表找到相同的key值返回对应的Value值即可

contain方法:

public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
}

contain方法同get类似,只是返回值不一样。

put方法:


 1 public V put(K key, V value) {
 2         return putVal(hash(key), key, value, false, true);
 3     }
 4 
 5 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
 6                    boolean evict) {
 7         Node<K,V>[] tab; Node<K,V> p; int n, i;
 8         if ((tab = table) == null || (n = tab.length) == 0)
 9             n = (tab = resize()).length;
10         if ((p = tab[i = (n - 1) & hash]) == null)
11             tab[i] = newNode(hash, key, value, null);
12         else {
13             Node<K,V> e; K k;
14             if (p.hash == hash &&
15                 ((k = p.key) == key || (key != null && key.equals(k))))
16                 e = p;
17             else if (p instanceof TreeNode)
18                 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
19             else {
20                 for (int binCount = 0; ; ++binCount) {
21                     if ((e = p.next) == null) {
22                         p.next = newNode(hash, key, value, null);
23                         if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
24                             treeifyBin(tab, hash);
25                         break;
26                     }
27                     if (e.hash == hash &&
28                         ((k = e.key) == key || (key != null && key.equals(k))))
29                         break;
30                     p = e;
31                 }
32             }
33             if (e != null) { // existing mapping for key
34                 V oldValue = e.value;
35                 if (!onlyIfAbsent || oldValue == null)
36                     e.value = value;
37                 afterNodeAccess(e);
38                 return oldValue;
39             }
40         }
41         ++modCount;
42         if (++size > threshold)
43             resize();
44         afterNodeInsertion(evict);
45         return null;
46     }

1,判断键值对数组tab[]是否为空或为null,否则以默认大小resize();
2,根据键值key计算hash值得到插入的数组索引i,如果tab[i]==null,直接新建节点添加,否则转入3
3,判断当前数组中处理hash冲突的方式为链表还是红黑树(check第一个节点类型即可),分别处理。

暂时先分析到这里,其他方法后面再分享。

posted on 2019-01-04 11:29  jameszheng  阅读(1569)  评论(0编辑  收藏  举报