【Java总结】HashMap源码分析及SparseArray对比

HashMap 这个集合用的多就不用说了,而且其hash函数的思想也贯穿了在编程的各个领域,甚至在nginx负载均衡的算法设计上也有其体现,因此详细的总结一下HashMap的设计思想是非常有意义的一件事情

如果大家看到这篇博客最好先复习一下上一篇的hashcode的设计,而且不要着急一下全掌握,用心的记录反复查看,一次没有掌握就多看几次;共勉

总结之前我也读了别人的几篇博客分析,如这里 ,技术本该这样互相学习,多多思想

同样我们依然带着问题去从源码层级去了解HashMap

HashMap的数据结构设计探究

在这里插入图片描述
除了HashMap的基础uml结构之外,我们还要有一个概念HashMap 是基于散列表的一个结构。说到散列表我们就需要先了解一下LinedList的一个结构,这个回头在单独详细说这里大致了解一下

在这里插入图片描述
我们要查找这集合中的某个元素,通常是通过遍历整个集合,需要O(N)的时间复杂度,但是如果数据量比较大的话这样的数据结构就会有很严重的性能问题。那么散列表是如何处理和解决这个问题呢

在这里插入图片描述
我们可以看到对于HashMap这个散列表结构,增加了hash函数和哈希的映射。这个结构最像我们查询汉语字典,(比如我们要查"达"这个字,我们先“计算出”其拼音[dá] ,在从相同的这个拼音里面找出具体的这个字,其中这个拼音就类似我们这里的hash函数)

这里就引申出来一个问题:

Hash函数要尽量的分散,既不能聚在一处,这样就行程了一条单链没什么意义,也不能完全分散这样就创建了多个节点也没有任何意义。

这个问题其实已经在我的博客《Java总结 - Hash算法和hashCode》里做了介绍,主要是通过

  • 生成hashCode的时候尽量散列:h = 31 * h + val[i]; 注意这里用31这个奇素数来处理
  • 定义hashMap的容量大小为2的幂次方n;为了更好的生成分散的hash数值;h = key.hashCode()) ^ (h >>> 16)
  • n-1&hash 计算得到当前key值的value值所处节点

通过这三步就完成了,上图的1,2,3的过程并且生成了一个可以用空间换取性能的一个散列表的结构。下面我们就结合代码具体看一下java的HashMap的实现

那么对于key值的hash存在重复以后数据存储怎么处理呢,也就是常说的hash冲突 ,一般有两种处理方式开放地址法链地址法

开放地址法
冲突产生的时候,可以在使用另种方式生成新的映射。如:存在冲突的key位置在一个散列表1的位置那么可以把新的这个放在2的位置上

链地址法
当遇到冲突了,直接往当前的数据往散列表链表里面填充即可。那么我们进行相同hash查询,需要遍历其子链表即可。如下图所示:

在这里插入图片描述
通过比较开放地址法 一旦冲突发生就可能联系发生多次hash计算从而导致性能的影响。而HashMap则使用第二种方式链地址法

基于jdk1.8探究一下源码

关键变量

  • 首先了解一下一些重要的常量的含义
 	/**
     * The default initial capacity - MUST be a power of two.
     * 默认的容量大小为16 并且如果自定义的话必须要是2的幂次方 ;这个可上面的解释
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大的容量,如果定义了一个比这个值更大,还是实用这个值
     * The maximum capacity, used if a higher value is implicitly specified
     *      * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     *常用的叫法叫加载因子,具体我们后面在进一步介绍
     capacity
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 这个参数是jdk1.8才加上的,主要作用是当一个链表上的容量超过这个数值的时候可能(注意是可能,因后面还有个参数控制)会转换成红黑树
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
    *这个参数是jdk1.8才加上的,主要作用是当一个链表上的容量小于这个数值的时候如果当前数据结构是红黑树的结构则要转换位链表
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
  	 当集合中的容量大于这个值时,表中的桶才能进行树形化 ,否则桶内				  元素太多时会扩容;而不是树形化 为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
  • 在了解一下一些重要的变量的含义

   /**
   	* 初始化使用,长度必须是 2的幂
    * The table, initialized on first use, and resized as
    * necessary. When allocated, length is always a power of two.
    * (We also tolerate length zero in some operations to allow
    * bootstrapping mechanics that are currently not needed.)
    */
 	transient Node<K,V>[] table;

    /**
    	缓存的entrySet
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * key-value键值对的数量 
     * The number of key-value mappings contained in this map.
     */
    transient int size;

    /**
     和ArrayList和LinkedList集合中的字段modCount一样,记录集合被修改的次数
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;

    /**
   	 * 调整大小后的大小值(容量*加载因子)。capacity * load factor
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;

    /**
      散列表的加载因子。
     * The load factor for the hash table.
     *
     * @serial
     */
    final float loadFactor;
  • Node<K,V>[] table HashMap 是由数组+链表+红黑树组成,这里的数组就是 table 字段。后面对其进行初始化长度默认是 DEFAULT_INITIAL_CAPACITY= 16。而且 JDK 声明数组的长度总是 2的n次方(一定是合数),为什么这里要求是合数,一般我们知道哈希算法为了避免冲突都要求长度是质数,这里要求是合数,下面在介绍 HashMap 的hashCode() 方法(散列函数) 上一篇博客也有提到《Java总结 - Hash算法和hashCode》

  • int size 记录key-value的对数

  • loadFactor 装载因子,是用来衡量 HashMap 满的程度,计算HashMap的实时装载因子的方法为:size/capacity,而不是占用桶的数量去除以capacity。capacity 是桶的数量,也就是 table 的长度length。
    默认的负载因子0.75 是对空间和时间效率的一个平衡选择,建议大家不要修改,除非在时间和空间比较特殊的情况下,如果内存空间很多而又对时间效率要求很高,可以降低负载因子loadFactor 的值;相反,如果内存空间紧张而对时间效率要求不高,可以增加负载因子 loadFactor 的值,这个值可以大于1。
    -threshold capacity * loadFactor。这个值是当前已占用数组长度的最大值。过这个数目就重新resize(扩容),扩容后的 HashMap 容量是之前容量的两倍

构造方法

  • 默认构造方法,一般如果不是特别的需要尽量使用默认构造方法即可
/**
     * 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 an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int initialCapacity, float loadFactor) {
    	//自定义的容量不能<0
        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);
    }
   /**
     * 返回大于等于initialCapacity的最小的二次幂数值。
     * >>>操作符表示无符号右移,高位取0。
     * | 按位或运算
     * Returns a power of two size for the given target capacity.
     */
    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;
    }

hash函数回顾

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

i = (table.length - 1) & hash;//这一步是在后面添加元素putVal()方法中进行位置的确定

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

这块如果在不明白就在看一下《Java总结 - Hash算法和hashCode》

添加元素

  /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key(通过hash函数计算的结果)
     * @param key the key(存储的key的值)
     * @param value the value to put(存储的value的值)
     * @param onlyIfAbsent if true, don't change existing value(true 表示不要更改现有值)
     * @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;
        //检查是否初始化,resize()函数扩容下面会详细分析
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //这一步比较关键,判断当前的key值是否存在冲突,如果不存在冲突的话就新建节点    
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {//tab[i] 不为null,表示该位置已经有值了
            Node<K,V> e; K k;
            //节点key已经有值了,直接用新值覆盖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 {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                         //链表长度大于8,转换成红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //key已经存在直接覆盖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;
        //超过最大容量,进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
  • 判断键值对数组 table 是否为空或为null,否则执行resize()进行扩容;

  • 根据键值key计算hash值得到插入的数组索引i

  • 判断table[i]的首个元素是否和key一样,如果相同直接覆盖value,否则转向④,这里的相同指的是hashCode以及equals;

  • 判断table[i] 是否为treeNode,即table[i] 是否是红黑树,如果是红黑树,则直接在树中插入键值对

  • 遍历table[i],判断链表长度是否大于8,大于8的话把链表转换为红黑树,在红黑树中执行插入操作,否则进行链表的插入操作;遍历过程中若发现key已经存在直接覆盖value即可;

  • 插入成功后,判断实际存在的键值对数量size是否超过了最大容量threshold,如果超过,进行扩容。

  • 如果新插入的key不存在,则返回null,如果新插入的key存在,则返回原key对应的value值(注意新插入的value会覆盖原value值)

if (++size > threshold)//超过最大容量,进行扩容
resize();
这里有超过最大容量进行扩容,HashMap 是由数组+链表+红黑树(JDK1.8)组成,如果在添加元素时,发生冲突,会将冲突的数放在链表上,当链表长度超过8时,会自动转换成红黑树。

注意这个sizethreshold的概念。size 表示键值对的数量 threshold = capacity * loadFactor

afterNodeAccess(e);
afterNodeInsertion(evict);
这都是一个空的方法实现,我们在这里可以不用管,但是在后面介绍 LinkedHashMap 会用到,LinkedHashMap 是继承的 HashMap,并且重写了该方法

扩容处理

我们知道jdk1.8之前HashMap的链没有红黑树的这个数据结构代码结构如下,大体的过程是创建一个新的大容量数组,然后依次重新计算原集合所有元素的索引,然后重新赋值。如果数组某个位置发生了hash冲突,使用的是单链表的头插入方法,同一位置的新元素总是放在链表的头部,这样与原集合链表对比,扩容之后的可能就是倒序的链表了。

    /**
      *@param newCapacity 为新数组的大小
      */
    void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        //已经达到最大(1>>>30 )了
        if (oldCapacity == MAXIMUM_CAPACITY) {
            //修改阈值为int的最大值(2^31-1),这样以后就不会扩容了
            threshold = Integer.MAX_VALUE;
            return;
        }
		//初始化一个新的Entry数组
        Entry[] newTable = new Entry[newCapacity];
        //将数组元素转移到新数组里面
        transfer(newTable, initHashSeedAsNeeded(newCapacity));
        table = newTable;
        //修改阈值
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }
    void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {//遍历数组
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                //重新计算每个元素在数组中的索引位置
                int i = indexFor(e.hash, newCapacity);
                //标记下一个元素,添加是链表头添加
                e.next = newTable[i];
                //将元素放在链上
                newTable[i] = e;
                //访问下一个 Entry 链上的元素
                e = next;
            }
        }
    }

jdk1.8以后的扩容实现如下,首先计算新桶数组容量newCap和新阈值newThr,然后从将原有数据存放到新的集合中


/**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        //如果原数组未初始化,长度为0
        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;
            }
            //原数组长度大于等于初始化长度16,并且扩大一倍也还是小于小于最大容量的话
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //扩容一倍     
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // 旧的阈值大于0,新容量直接等于新阈值
            newCap = oldThr;
        else {  //否则就直接赋值为初始化的值
            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) {
        	//这里把每个bucket都移动到新的buckets中
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;//原数据置为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;
    }

在这里插入图片描述
相比于JDK1.7,1.8使用的是2次幂的扩展(指长度扩为原来2倍),所以,元素的位置要么是在原位置,要么是在原位置再移动2次幂的位置。我们在扩充HashMap的时候,不需要像JDK1.7的实现那样重新计算hash,只需要看看原来的hash值新增的那个bit是1还是0就好了,是0的话索引没变,是1的话索引变成“原索引+oldCap

删除元素

public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    /**
     * Implements Map.remove and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
    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;
        //桶数组不为null,并且已经存在值,同时能查找到对应的节点
        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;
    }

HashMap 删除元素首先是要找到 桶的位置,然后如果是链表,则进行链表遍历,找到需要删除的元素后,进行删除;如果是红黑树,也是进行树的遍历,找到元素删除后,进行平衡调节,注意,当红黑树的节点数小于 6 时,会转化成链表。

afterNodeRemoval(node);
这里是空的实现,在LinkedHashMap里用作维护删除节点后的前后位置关系

元素查找

public V get(Object key) {
        Node<K,V> e;
        //根据hash的索引和key值去查询对应的value
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    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;
    }

    /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    /**
     * Returns <tt>true</tt> if this map maps one or more keys to the
     * specified value.
     *
     * @param value value whose presence in this map is to be tested
     * @return <tt>true</tt> if this map maps one or more keys to the
     *         specified value
     */
    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;
    }

首先通过 key 找到计算索引,找到桶位置,先检查第一个节点,如果是则返回,如果不是,则遍历其后面的链表或者红黑树。其余情况全部返回 null。

遍历元素

这里我只写一下两个性能上较好的写法,至于通过ketSet方式拿到key值在做遍历的一般不推荐使用

Set<Map.Entry<String,Object>> entrySet = map.entrySet();
 for(Map.Entry<String,Object> entry : entrySet){
      System.out.println(entry.getKey()+"-"+entry.getValue());
 }

下面这种迭代器的方式可以在遍历的时候进行动态删除。

Iterator<Map.Entry<String,Object>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
    Map.Entry<String,Object> mapEntry = iterator.next();
    System.out.println(mapEntry.getKey()+"-"+mapEntry.getValue());
}

HashMap总结

  • 本文主要基于JDK1.8的HashMap是由数组+链表+红黑树的结构进行简单分析,当链表长度超过 8 时会自动转换成红黑树,当红黑树节点个数小于 6 时,又会转化成链表。相对于早期版本的 JDK HashMap 实现,新增了红黑树作为底层数据结构,在数据量较大且哈希碰撞较多时,能够极大的增加检索的效率。

  • 允许 key 和 value 都为 null。key 重复会被覆盖,value 允许重复。

  • 非线程安全

  • 无序(遍历HashMap得到元素的顺序不是按照插入的顺序)

SpareArray的数据结构设计探究

SpareArray是anroid.util 包下面的一个集合类,主要用于在数据量小的情况下的一种节省内存的一种key-value结构,并且key值固定为key减少了装箱和拆箱的内存消耗。而且是一种用性能换空间的一种结构

那么我们还是通过源码来看一下SpareArray和HashMap的主要区别

关键变量和构造器

public class SparseArray<E> implements Cloneable {
	//已经删除的标记
    private static final Object DELETED = new Object();
    //是否需要Gc
    private boolean mGarbage = false;

	//key的数组
    private int[] mKeys;
    //value的数组
    private Object[] mValues;
    //容器key-value数量
    private int mSize;

    /**
     * Creates a new SparseArray containing no mappings.
     */
    public SparseArray() {
        this(10);
    }

    /**
     * Creates a new SparseArray containing no mappings that will not
     * require any additional memory allocation to store the specified
     * number of mappings.  If you supply an initial capacity of 0, the
     * sparse array will be initialized with a light-weight representation
     * not requiring any additional array allocations.
     */
    public SparseArray(int initialCapacity) {
    	// 如果初始化容量是0的话就默认初始化
        if (initialCapacity == 0) {
            mKeys = EmptyArray.INT;
            mValues = EmptyArray.OBJECT;
        } else {
        	//这里我们看一下生成一个obj的数组的方法
            mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);
            mKeys = new int[mValues.length];
        }
        mSize = 0;
    }

ArrayUtils.newUnpaddedObjectArray

public static Object[] newUnpaddedObjectArray(int minLen) {
        return (Object[])VMRuntime.getRuntime().newUnpaddedArray(Object.class, minLen);
    }

插入元素

public void put(int key, E value) {
        //利用二分查找,找到 待插入key 的 下标index
        int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
        //如果返回的index是正数,说明之前这个key存在,直接覆盖value即可
        if (i >= 0) {
            mValues[i] = value;
        } else {
            //若返回的index是负数,说明 key不存在.
            //先对返回的i取反,得到应该插入的位置i
            i = ~i;
            //如果i没有越界,且对应位置是已删除的标记,则复用这个空间
            if (i < mSize && mValues[i] == DELETED) {
                //赋值
                mKeys[i] = key;
                mValues[i] = value;
                return;
            }
            
            //如果需要GC,且需要扩容
            if (mGarbage && mSize >= mKeys.length) {
                //先触发GC
                gc();
                //gc后,下标i可能发生变化,所以再次用二分查找找到应该插入的位置i
                // Search again because indices may have changed.
                i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
            }
            //插入key(可能需要扩容)
            mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
            //插入value(可能需要扩容)
            mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
            //集合大小递增
            mSize++;
        }
    }

ContainerHelpers.binarySearch

    //二分查找的基础写法
    static int binarySearch(int[] array, int size, int value) {
        int lo = 0;
        int hi = size - 1;

        while (lo <= hi) {
            //关注一下高效位运算
            final int mid = (lo + hi) >>> 1;
            final int midVal = array[mid];

            if (midVal < value) {
                lo = mid + 1;
            } else if (midVal > value) {
                hi = mid - 1;
            } else {
                return mid;  // value found
            }
        }
        //若没找到,则lo是value应该插入的位置,是一个正数。对这个正数去反,返回负数回去
        return ~lo;  // value not present
    }
    
    //垃圾回收函数,压缩数组
    private void gc() {
        //保存GC前的集合大小
        int n = mSize;
        //既是下标index,又是GC后的集合大小
        int o = 0;
        int[] keys = mKeys;
        Object[] values = mValues;
        //遍历values集合,以下算法 意义为 从values数组中,删除所有值为DELETED的元素
        for (int i = 0; i < n; i++) {
            Object val = values[i];
            //如果当前value 没有被标记为已删除
            if (val != DELETED) {
                //压缩keys、values数组
                if (i != o) {
                    keys[o] = keys[i];
                    values[o] = val;
                    //并将当前元素置空,防止内存泄漏
                    values[i] = null;
                }
                o++;
            }
        }
        //修改 标识,不需要GC
        mGarbage = false;
        //更新集合大小
        mSize = o;
    }

GrowingArrayUtils.insert方法如下

 public static int[] insert(int[] array, int currentSize, int index, int element) {
        //断言 确认 当前集合长度 小于等于 array数组长度
        assert currentSize <= array.length;
        //如果不需要扩容
        if (currentSize + 1 <= array.length) {
            //将array数组内元素,从index开始 后移一位
            System.arraycopy(array, index, array, index + 1, currentSize - index);
            //在index处赋值
            array[index] = element;
            //返回
            return array;
        }
        //需要扩容
        //构建新的数组
        int[] newArray = new int[growSize(currentSize)];
        //将原数组中index之前的数据复制到新数组中
        System.arraycopy(array, 0, newArray, 0, index);
        //在index处赋值
        newArray[index] = element;
        //将原数组中index及其之后的数据赋值到新数组中
        System.arraycopy(array, index, newArray, index + 1, array.length - index);
        //返回
        return newArray;
    }
    //根据现在的size 返回合适的扩容后的容量
    public static int growSize(int currentSize) {
        //如果当前size 小于等于4,则返回8, 否则返回当前size的两倍
        return currentSize <= 4 ? 8 : currentSize * 2;
    }

删除元素

SparseArray作为一个轻量级的集合,删除的方法也比较的简单,没有特别多需要关注的,主要就是查询通过二分查找法查询是否存在key,并且把对value对象置为删除的标记

    public void remove(int key) {
        delete(key);
    }

    public void delete(int key) {
        //二分查找得到要删除的key所在index
        int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
        //如果存在元素
        if (i >= 0) {
            //修改values数组对应位置为已删除的标志DELETED
            if (mValues[i] != DELETED) {
                mValues[i] = DELETED; 
                //并修改 mGarbage ,表示稍后需要GC
                mGarbage = true;
            }
        }
    }
 //按照游标删除
 public void removeAt(int index) {
        //根据index直接索引到对应位置 执行删除操作
        if (mValues[index] != DELETED) {
            mValues[index] = DELETED;
            mGarbage = true;
        }
    }
 //批量删除
  public void removeAtRange(int index, int size) {
   	   //越界处理
       final int end = Math.min(mSize, index + size);
       for (int i = index; i < end; i++) {
           removeAt(i);
       }
   }   

元素查询

	/*根据key值判断*/
    public E get(int key) {
        return get(key, null);
    }

    //按照key查询,如果key不存在,返回valueIfKeyNotFound
    public E get(int key, E valueIfKeyNotFound) {
        //二分查找到 key 所在的index
        int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
        //不存在则返回valueIfKeyNotFound
        if (i < 0 || mValues[i] == DELETED) {
            return valueIfKeyNotFound;
        } else {
            return (E) mValues[i];
        }
    }


  public int keyAt(int index) {
    	//按照下标查询时,先看是否需要执行gc函数
        if (mGarbage) {
            gc();
        }
        return mKeys[index];
    }
    
    public E valueAt(int index) {
    	 //按照下标查询时,先看是否需要执行gc函数
        if (mGarbage) {
            gc();
        }

        return (E) mValues[index];
    }
    public int indexOfKey(int key) {
     	//按照下标查询时,先看是否需要执行gc函数
        if (mGarbage) {
            gc();
        }
        //二分查找返回 对应的下标 ,可能是负数
        return ContainerHelpers.binarySearch(mKeys, mSize, key);
    }
    //如果多个key值对应同一个value,返回最靠前的那一个,后面就不做
    public int indexOfValue(E value) {
    	//按照下标查询时,先看是否需要执行gc函数
        if (mGarbage) {
            gc();
        }
        //不像key一样使用的二分查找。是直接线性遍历去比较,而且不像其他集合类使用equals比较,这里直接使用的 ==
        //如果有多个key 对应同一个value,则这里只会返回一个更靠前的index
        for (int i = 0; i < mSize; i++)
            if (mValues[i] == value)
                return i;

        return -1;
    }

HashMap 和SpareArray的比较

  • 空间
    HashMap的内部数组长度必须是2n,需要大一些降低碰撞概率(可以通过负载因子调节),数组元素是跳跃的,需要为键值对创建Node对象并判断是否冲突。
    SpareArray则是通过牺牲性能换取空间,没有2n限制,数组长度无需太长,size范围内没有闲置位置,无需为键值对创建Node对象。

  • 查找
    HashMap在元素非常多时性能要高于SpareArray。
    HashMap直接通过hash值位运算计算出下标,SpareArray需要通过二分法查找;hash碰撞冲突时HashMap只需遍历链表活红黑树,SpareArray需要分别向后向前遍历数组。

  • 增删
    这个几乎就是(LinkedList,红黑树)和ArrayList的区别了

  • 扩容
    这个是ArrayMap优于HashMap的地方。
    HashMap的下标位置是和数组容量相关的,带来一个问题,jdk1.7每次数组容量改变都需要重新计算所有键值对的下标,也就是rehash。jdk1.8的时候有树的结构重新定义结构 而SpareArray则没有这个问题,只需要创建一个更大的数组,用System.arrayCopy把元素复制过去。

  • 遍历
    HashMap需要遍历数组和数组中的每一个单向链表,并且数组元素是跳跃的;SpareArray则只用遍历一个连续的mArray数组即可

  • 选择
    可以看出SpareArray适合数量不多、对内存敏感、频繁扩容的地方,而在元素比较多时HashMap更优

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值