Java 集合学习--HashMap

一、HashMap 定义

HashMap 是一个基于散列表(哈希表)实现的键值对集合,每个元素都是key-value对,jdk1.8后,底层数据结构涉及到了数组、链表以及红黑树。目的进一步的优化HashMap的性能和效率。允许key和value为NULL,同样非线程安全。

①、继承AbstractMap抽象类,AbstractMap实现Map接口,实现部分方法的。同样在上面HashMap的结构中,HashMap同样实现了Map接口,这样做是否有什么深层次的用意呢?网上查阅资料发现,这种写法只是一种失误,在java集合框架中发现很多这种写法,不用过于在乎这种失误。

②、实现Map接口,Map类的顶层接口,Map接口定义了一组键值对映射通用的操作。储存一组成对的键-值对象,提供key(键)到value(值)的映射,Map中的key不要求有序,不允许重复。value同样不要求有序,但可以重复。

③、实现 Cloneable 接口和Serializable接口,分别支持对象的克隆与对象的序列化

二、字段属性

//1.序列化版本标记,序列化与反序列化时发挥作用
private static final long serialVersionUID = 362498820763181265L;
//2.HashMap集合默认初始化容量,1*2的4次方,即16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4
//3.集合最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//4.默认的加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//5.当桶(bucket)上的结点数大于这个值时会转成红黑树(JDK1.8新增)
static final int TREEIFY_THRESHOLD = 8;
//6.当bucket上的节点数少于这个值得时候,数转化成链表
static final int UNTREEIFY_THRESHOLD = 6;
//7.当集合的容量大于这个值的时候,HashMap中桶的节点进行树形化
static final int MIN_TREEIFY_CAPACITY = 64;
//8.Node数组,Node是HashMap中自定义hash节点类。
transient Node<K,V>[] table;
//9.保存缓存的entrySet
transient Set<Map.Entry<K,V>> entrySet;
//10.集合元素个数,即HashMap中键值对的个数
transient int size;
//11.集合修改次数
transient int modCount
//12.下次扩容的临界值,通常称为阀值,等于capacity * load factor
int threshold;
//13.散列表的加载因子,可自己指定
final float loadFactor;

三、构造方法

①、默认无参构造器,设置加载因子为默认加载因子0.75

②、带参构造器

1)指定初始化容量,使用默认加载因子

2)指定初始化容量,使用自定加载因子

四、常用方法

1.添加元素(键值对)

//添加键值对
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
}
-------------------------------------------------------------------------
//具体的步骤
//1.通过key计算hash值
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//2.如果table数组为null,初始化数组,通过hash值确定键值对在数组中的索引位置
//3.确定元素在数组中的位置后,判断那个位置的元素的key是否与添加的key一样,如果一致则直接覆盖老的键值对,如果不一样则判断结点的类型,是否是树,如果是树则在树中插入一个新构造的树结点
//4.如果数组对应位置上的节点不是树,则是链表,这个时候要么在链表的最后插入新的Node节点,要么是当发现链表的节点个数大于8,并且集合元素个数大于64的时候,则将链表转换成红黑树,要么则是进行扩容。
-------------------------------------------------------------------------
//具体细节如下:
/**
     * Implements Map.put and related methods
     *
     * @param hash hash for key    哈希值
     * @param key the key    键
     * @param value the value to pu    t值
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode. false表示table处于创建模式
     * @return previous value, or null if none
     */
    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;//首次进行数组的初始化,resize主要用来进行扩容的
        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;
}
View Code

2.查找元素(键值对)

①、通过 key 查找 value,首先通过key计算hash值,再根绝hash值确定key在所在数组的索引位置后,最后遍历其后面的链表或者红黑树找到对应的value.

public V get(Object key) {
        Node<K,V> e;
        //确定key的hash值,计算方法与插入的时候一致
        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) {//数组不为空,并且在相关的位置存在Node结点。
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))//如果在第一个位置存在则直接返回Nnode结点
                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或者 value,

//判断集合中是否存在某个键,原理与查找键值类似
public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
}
//遍历整个数组,明显效率很低
public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null && size > 0) {
            //遍历桶
            for (int i = 0; i < tab.length; ++i) {
                //遍历桶中的每个节点元素
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

3.删除元素(键值对),删除的原理本质上是类似通过key查找value,首先通过key计算hash值,通过hash值确定key在散列表中的位置,由于key不重复,所以确定位置后,要么是遍历链表,要么遍历红黑树找到对应key所在的节点,找到node节点后删除。

public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
    
    final Node<K,V> removeNode(int hash, Object key, Object value,
            boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        //(n - 1) & hash找到桶的位置
        if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        //如果键的值与链表第一个节点相等,则将 node 指向该节点
        if (p.hash == hash &&
        ((k = p.key) == key || (key != null && key.equals(k))))
        node = p;
        //如果桶节点存在下一个节点
        else if ((e = p.next) != null) {
            //节点为红黑树
        if (p instanceof TreeNode)
         node = ((TreeNode<K,V>)p).getTreeNode(hash, key);//找到需要删除的红黑树节点
        else {
         do {//遍历链表,找到待删除的节点
             if (e.hash == hash &&
                 ((k = e.key) == key ||
                  (key != null && key.equals(k)))) {
                 node = e;
                 break;
             }
             p = e;
         } while ((e = e.next) != null);
        }
        }
        //删除节点,并进行调节红黑树平衡
        if (node != null && (!matchValue || (v = node.value) == value ||
                      (value != null && value.equals(v)))) {
        if (node instanceof TreeNode)
         ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
        else if (node == p)
         tab[index] = node.next;
        else
         p.next = node.next;
        ++modCount;
        --size;
        afterNodeRemoval(node);
        return node;
        }
        }
        return null;
    }
View Code

4.遍历集合,map的遍历方法有多种,通常推荐的迭代器遍历,不过遍历的本质都是循环整个table数组,对数组的每个桶进行遍历。

 1 public class HashMapDemo {
 2     
 3     public static void main(String[] args) {
 4         
 5         HashMap<String, String> map = new HashMap<>();
 6         map.put("1", "a");
 7         map.put("2", "b");
 8         map.put("3", "c");
 9         //通过获取所有的key后,再通过key获取value的方式遍历
10         for(String str : map.keySet()){
11             System.out.print(map.get(str)+" ");
12         }
13         System.out.println("\n----------------");
14         for(Entry entry : map.entrySet()){
15             System.out.println(entry.getKey()+" "+entry.getValue());
16         }
17     }
18 
19 }

输出结果:

a b c 
----------------
1 a
2 b
3 c

四、HashMap的hash值得秘密

1.HashMap 是数组+链表+红黑树的组合,hash值主要牵扯到它在hash表,也叫散列表中的位置。Hash表是一种根据关键字值(key - value)而直接进行访问的数据结构。也就是说它通过把关键码值映射到表中的一个位置来访问记录,它的查找速度非常快,查找一个元素可用通过key的hash值直接确定所在的位置。HashMap中确定key的值有其特定的算法,并且最终确定在散列表中的位置还需要经过&运算。具体如下:

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
    i = (table.length - 1) & hash;//这一步是在后面添加元素putVal()方法中进行位置的确定

主要分为三步:

  ①、取 hashCode 值: key.hashCode(),注意hashcode()的值是key对象在堆中的地址经过特殊的hahs算法映射后的一个int值

  ②、高位参与运算:h>>>16

  ③、取模运算:(n-1) & hash,注意:在n是偶数的时候,(n-1)&hash==hash%n;这也是为什么HashMap的容量为2的n次方的原因,便于使用按位与运算代替取模,因为位运算的速度远快于取模。这是一种优化。

2.为什么要进行(h = k.hashCode()) ^ (h >>> 16)?

通过hashCode()的高16位 异或 低16位实现的:(h = k.hashCode()) ^ (h >>> 16),主要是从速度、功效、质量来考虑的,这么做可以在数组table的length比较小的时候,也能保证考虑到高低Bit都参与到Hash的计算中,同时不会有太大的开销。具体如下:

五、HashMap的扩容机制

当HashMap 集合的元素已经大于了最大承载容量threshold(capacity * loadFactor)的时候,会进行扩容,即扩大数组的长度。通常不指定集合容量的时候,初始容量为16.阀值为12.当集合的元素个数大于12的时候,集合进行扩容,扩大打原来集合的2倍大小,如下初始集合的首次扩容为32,依次是64,128。对应的阀值进行变化。依次为24,48,96。在扩容的同时,需要重新进行键值对的hash映射。在jdk1.8之前,扩容首先是创建一个新的大容量数组,然后依次重新计算原集合所有元素的索引,然后重新赋值。如果数组某个位置发生了hash冲突,使用的是单链表的头插入方法,同一位置的新元素总是放在链表的头部,这样与原集合链表对比,扩容之后的可能就是倒序的链表了。在jdk1.8后,进行进一步的优化,使扩容的时候具体细节如下:

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

从上面的源码可以看出,容量的增长是成倍增长,容量的大小为2的n次幂,那么扩容的时候,元素的key的hash值要么在原来位置不变,要么在原来的位置再移动2次幂的位置。不需要再次进行按位与运算,进一步优化扩容的机制。仅仅需要看看原来的hash值新增的那个bit是1还是0就好了,是0的话索引没变,是1的话索引变成“原索引+oldCap”。

六、总结

  • HashMap中两个重要的属性,初始容量和加载因子,这两个属性影响HashMap的性能,它的设值需要非常谨慎。初始容量是创建哈希表时的容量,加载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度,两者决定何时进行扩容。
  • HashMap中key和value都允许为null。
  • 哈希表的容量一定要是2的整数次幂,length为2的整数次幂的话,h&(length-1)就相当于对h%length,这样便保证了散列的均匀,使不同hash值发生碰撞的概率,同时也提升了效率。

猜你喜欢

转载自www.cnblogs.com/liupiao/p/9346209.html