android真实面试题全解析

【Android必问面试题】HashMap相关问题

2021-04-07  本文已影响0人  不做android
什么是HashMap?

简单来说HashMap是数组+链表的结合体,Jdk1.8后加入了红黑树,数组是HashMap的主体,链表和红黑树的出现主要是为了解决哈希冲突。HashMap继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。

HashMap的存储

HashMap是根据键值对来对数据进行存储,大多数情况下只需要一次定位即可,因此具有很快的访问速度。HashMap中最多可以有一条记录的键为null,null键的hash值为0,允许多条记录的值为null。
HashMap是线程不安全的,如果想要保证线程安全可以用Collections的synchronizedMap 方法使 HashMap 具有线程安全的能力,或者使用ConcurrentHashMap。

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;//当前节点的hash值
        final K key;//保存节点的key值
        V value;//保存节点的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;
        }
    }
//链表部分
 static class LinkedHashMapEntry<K,V> extends HashMap.Node<K,V> {
        LinkedHashMapEntry<K,V> before, after;
        LinkedHashMapEntry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }
//红黑树部分
static final class TreeNode<K,V> extends LinkedHashMap.LinkedHashMapEntry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links 存储当前节点的父节点
        TreeNode<K,V> left;//存储当前节点的做孩子节点
        TreeNode<K,V> right;//存储当前节点的右孩子节点
        TreeNode<K,V> prev;    // needed to unlink next upon deletion存储当前节点的前一个节点
        boolean red;//存储当前节点的红黑颜色
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

从以上可以很清晰地看出来HashMap是数组+链表+红黑树实现的。

从源码真正的了解HashMap
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);
    }
static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;//>>>代表无符号右移 
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
HashMap 的put方法

在看put方法前,先了解一下HashMap中定义的各种变量的作用

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;

HashMap的put方法

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
 final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            //在构造方法中调用时table一定为null
            if (table == null) { // pre-size
                //根据传入的map的大小计算要创建的hashMap的大小。
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);//把创建的hashmap 的大小存起来
            }
            else if (s > threshold)//如果传进来的map的大小大于当前大小要先进行扩容
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                //扩容之后将数据进行插入。
                putVal(hash(key), key, value, false, evict);
            }
        }
    }
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;
        //确定在数组中的插入位置,位置计算通过(n - 1) & hash,也就是hash%n来得到,如果没有元素则直接插入
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //如果存在元素则比较待插入元素的hash值和key值
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
              //如果元素是红黑树节点则通过putTreeVal插入
                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);
                        //插入后的节点数如果大于TREEIFY_THRESHOLD - 1则要转变为红黑树
                        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 该元素已经存在,覆盖value
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;//记录变化次数
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
  final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K,V> root = (parent != null) ? root() : this;
            //从根节点开始遍历找到合适的位置
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;//dir小于0,接下来查找当前节点左孩子
                else if (ph < h)
                    dir = 1;//dir大于0,接下来查找当前节点右孩子
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))//hash值相同并且key相同
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                      //至此代表当前节点与待插入节点key不同,hash值相同
                      //k并未实现comparable<K>接口或者k的compareTo方法错误
                    if (!searched) {
                    //在以当前节点为根的整个树进行一次遍历,看是否存在待插入节点
                        TreeNode<K,V> q, ch;
                        searched = true;
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    //通过另一种方式比较k
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
              //插入节点
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    //平衡二叉树
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }
static int tieBreakOrder(Object a, Object b) {
            int d;
            if (a == null || b == null ||
                (d = a.getClass().getName().
                 compareTo(b.getClass().getName())) == 0)
                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                     -1 : 1);
            return d;
        }
HashMap 的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)//若定位到的节点是 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;
    }
final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
            TreeNode<K,V> p = this;
            do {
                int ph, dir; K pk;
                TreeNode<K,V> pl = p.left, pr = p.right, q;
                if ((ph = p.hash) > h)
                    p = pl;
                else if (ph < h)
                    p = pr;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &&
                         (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }
HashMap的扩容

首先我们在扩容的时候,一般会把长度扩为原来的2倍,所以,元素有可能保持在原位,或者移动2次幂的位置,也就是原来的hash值会新增一个bit,是0的话代表保持原位,1的话代表索引发生改变,这时的索引变为元索引+oldCap

下面具体看一下源码是什么样的。

 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        //oldCap为原table的大小
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //oldThr为oldCap*load_factor
        int oldThr = threshold;
        int newCap, newThr = 0;
        //resize()实在size>threshold的时候被调用。
        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
        }
        //下面是在table为空的时候被调用,oldCap小于等于0并且oldThr大于0,
        //表示用户使用的带参构造函数创建的hashMap,
        //导致oldTab为null,oldCap为0,oldThr不为0
        
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //oldCap 小于等于 0 且 oldThr 等于0,
        //用户调用 HashMap()构造函数创建的 HashMap,所有值均采用默认值,
        //oldTab(Table)表为空,oldCap为0,oldThr等于0,
        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) {
        //把 oldTab 中的节点 reHash 到 newTab 中去
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                    //若节点是单个节点,直接在 newTab中进行重定位
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                    //若节点是 TreeNode 节点,要进行 红黑树的 rehash 操作
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                            //若是链表,进行链表的 rehash操作
                            //loHead,下标不变情况下的链表头
                            //loTail,下标不变情况下的链表尾
                            //hiHead,下标改变情况下的链表头
                            //hiTail,下标改变情况下的链表尾
                        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判断节点位置rehash后是否发生改变
                            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;
                            // rehash后节点新的位置一定为原来基础上加上 oldCap
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
            TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
            TreeNode<K,V> loHead = null, loTail = null;
            TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            //由于TreeNode节点之间存在双端链表的关系,可以利用链表关系进行rehash
            for (TreeNode<K,V> e = b, next; e != null; e = next) {
                next = (TreeNode<K,V>)e.next;
                e.next = null;
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null)
                        loHead = e;
                    else
                        loTail.next = e;
                    loTail = e;
                    ++lc;
                }
                else {
                    if ((e.prev = hiTail) == null)
                        hiHead = e;
                    else
                        hiTail.next = e;
                    hiTail = e;
                    ++hc;
                }
            }
            //rehash 操作之后注意对根据链表长度进行untreeify或treeify操作
            if (loHead != null) {
                if (lc <= UNTREEIFY_THRESHOLD)
                    tab[index] = loHead.untreeify(map);
                else {
                    tab[index] = loHead;
                    if (hiHead != null) // (else is already treeified)
                        loHead.treeify(tab);
                }
            }
            if (hiHead != null) {
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map);
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
        }

HashMap,ConcurrentHashMap,HashTable的区别

上一篇下一篇

猜你喜欢

热点阅读