17、集合--HashMap

 

HashMap的基本方法测试:

    public static void main(String[] args) {

        HashMap<String,Student> map = new HashMap<>();

        Student student1 = new Student("aa",5);
        Student student2 = new Student("cc",1);
        Student student3 = new Student("bb",9);
        Student student4 = new Student("dd",7);

        //存放键值对
        map.put("a",student1);
        map.put("c",student2);
        map.put("b",student3);
        map.put("d",student4);
        System.out.println("添加数据之后的map:" + map);

        //通过键获取值
        System.out.println("获取key = d 的 value :" + map.get("d"));

        //判断是否为空
        System.out.println("为空:" + map.isEmpty());

        //获取map的容量
        System.out.println("大小:" + map.size());

        //判断映像中是否存在关键字key
        System.out.println("是否存在key = d 的关键字 :" + map.containsKey("d"));
        //判断映像中是否存在value
        System.out.println("是否存在value=student1 : " + map.containsValue(student1));

        //返回映像值中所有的值的视图集
        System.out.println("所有值的视图集:" + map.values());

        //所有键的视图集
        System.out.println("所有键的视图集:" + map.keySet());

        //遍历
        Iterator it = map.keySet().iterator();
        while (it.hasNext()){
            String key = (String) it.next();
            System.out.println("遍历" + key + "=" + map.get(key));
        }

        //返回Map.entry对象的视图集
        System.out.println("返回Map.entry对象的视图集:" + map.entrySet());

        //移除指定key--value
        map.remove("d");
        System.out.println("移除key = d的之后的map:" + map);

        //清空map
        map.clear();
        System.out.println("清空之后的map:" + map);
    }

Student类同时重写hashCode和equals方法

public class Student {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Student() {
        super();
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
}

 

底层数据的存储结构

 

基本方法的底层解析

https://zhuanlan.zhihu.com/p/28501879可参考其中的相关说明,本人也是借鉴相关说明顺序

1、实例化对象HashMap<String,Student> map = new HashMap<>();

初始化一个负载因子,负载因子默认是0.75f

private static final long serialVersionUID = 362498820763181265L;
    static final int MAXIMUM_CAPACITY = 1 << 30;
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    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;//修改次数
    int threshold;
    final float loadFactor;
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

Node类

用来保存网Map里存放数据

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

 

2、put(K key, V value):向map中存入数据

注意这里重写equals方法同时一定要重写hashCode方法

将键(key)和值(value)传入put()方法中

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

hash(Object key)方法

此时将传入的key值调用hash()方法

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

 putVal()方法

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
      
   Node
<K,V>[] tab;
     Node<K,V> p;
     int n, i;

    //将table的值赋给tab在判断是否等于null,同时判断其长度是否等于0
if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;//放入的第一个元素时table为空,会触发resize方法

     //首先计算i的值 i = (n -1) & h
     //此时的p = tab[i]
     //在取判断p是否等于null
     //如果等于null 用key,value构造一个Node对象放入数组鞋标为i的位置
    
     //再次添加数据经过(n- 1) & hash算出在数组下标的位置
if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null);
else { Node<K,V> e; K k;
        //判断table[i]的首个元素是否和key一样,如果相同直接覆盖
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 {

      //如果计算数组下标两个相同产生了冲突:

      //此时是执行下面的循环
      //下方表明红色部分很重要
      //类似单链表的方式将上一个实例Node的对象的next指向此时新的Node对象
for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null);
              //当链表长度达到8时,将链表转为红黑色来处理
              //加入了红黑树是为了放置哈希表撞击,当链表的长度为8时,及时转为红黑树,提高map的效率
              
if (binCount >= TREEIFY_THRESHOLD - 1) // TREEIFY_THRESHOLD = 8 treeifyBin(tab, hash);//把链表转为红黑色 break; }
            //keu已经存在直接覆盖value
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;

    //插入出成功之后,判断实际存在的键值对对数量size是否超过了做大容量threshold,超过了进行扩容
if (++size > threshold) resize();//扩容就是重新计算容量 afterNodeInsertion(evict); return null; }

 resize()方法

当放入第一个元素时会触发resize()方法这些关键代码:

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; == 16

关键是当我们放入第一个元素时

如果底层的数组还是null,系统会初始化一个长度为16的Node数组,与ArrList的初始化很项

最后返回数组

虽然数组的长度等于16但是长度size依然是0

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

关于haash()方法是hashMap自己写的一个方法用来计算hash的值

 

HashMap的最底层是数组来实现的,数组里的元素可能为null,也有可能是单个对象,还有可能是单向链表或是红黑树。

文中的resize在底层数组为null的时候会初始化一个数组,不为null的情况下会去扩容底层数组,并会重排底层数组里的元素。

 

3、get()方法通过key取value

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

 getNode()

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab;//Entry对象数组

   Node<K,V> first, e; //在tab数组中经过散列的第一个位置

     int n; K k;
     //找到插入的第一个Node,方法是hash值和n-1相同 ,tab[(n-1)] & hash
     //也就是说在一条链上的hash相同
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
       //检查第一个Node对象是不是要找的Node
if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first;
        //检查first后面的Node
if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key);
          //遍历后面的链表,找到key值和hash值相同的Node
do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }

 get(key)方法时获取key的hash值,计算hash&(n-1)得到在链表数组中的位置first=tab[hash&(n-1)],

先判断first的key是否与参数key相等,不等就遍历后面的链表找到相同的key值返回对应的Value值即可

 

 4、containsKey()方法

调用的方法同上

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

 

5、containsValue()方法

此时定义一个临时的数组用于存放

然后对table进行遍历并且使用equlas方法进行比对

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

 

 6、values()

    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }

 

 7、KeySet()

    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

 

 8、entrySet()

   public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

 

 9、remove()

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

 

 10、clear()

public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

 

HashMap的扩容机制resize()

构造hash表时,如果不指明初始大小,默认大小为16(即Node数组大小16),

如果Node[]数组中的元素达到(填充比*Node.length)

重新调整HashMap大小 变为原来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 }
    //如果旧表的长度为0,就是说第一次初始化表
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;//把新表赋值给table 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)//说明这个node没有链表直接放在新表的e.hash & (newCap - )位置 newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);

            //如果e后边有链表,到这里表示e后面带着单链表,需要遍历单链表
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;//记录下一个节点
                //新表是旧表的两倍,实例上就把单链表拆分两队
                //e.hash & oldCap为偶数一堆 e.hash & oldCap为奇数对
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队不为null,放在在新表原位置 loTail.next = null; newTab[j] = loHead; } if (hiTail != null) {//hiTail队不为null,放在新表j + oldCap位置 hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
posted @ 2019-05-12 16:26  MrChengs  阅读(217)  评论(0编辑  收藏  举报