想看我更多文章:【张旭童的博客】http://blog.csdn.net/zxt0601
想来gayhub和我gaygayup:【mcxtzhang的Github主页】https://github.com/mcxtzhang

1 概述

在上文中,我们已经聊过了HashMapLinkedHashMap.所以如果没看过上文,请先阅读面试必备:HashMap源码解析(JDK8) ,面试必备:LinkedHashMap源码解析(JDK8
那么今天换点口味,不看JDK了,我们看看android sdk的源码。

本文将从几个常用方法下手,来阅读ArrayMap的源码。
按照从构造方法->常用API(增、删、改、查)的顺序来阅读源码,并会讲解阅读方法中涉及的一些变量的意义。了解ArrayMap的特点、适用场景。

如果本文中有不正确的结论、说法,请大家提出和我讨论,共同进步,谢谢。

2 概要

概括的说,ArrayMap 实现了implements Map<K, V>接口,所以它也是一个关联数组、哈希表。存储以key->value 结构形式的数据。它也是线程不安全的,允许key为null,value为null

它相比HashMap空间效率更高

它的内部实现是基于两个数组
一个int[]数组,用于保存每个item的hashCode.
一个Object[]数组,保存key/value键值对。容量是上一个数组的两倍
它可以避免在将数据插入Map中时额外的空间消耗(对比HashMap)。

而且它扩容的更合适,扩容时只需要数组拷贝工作,不需要重建哈希表

HashMap相比,它不仅有扩容功能,在删除时,如果集合剩余元素少于一定阈值,还有收缩(shrunk)功能。减少空间占用。

对于哈希冲突的解决,查看源码可以得知采用的是开放地址法

但是它不适合大容量的数据存储。存储大量数据时,它的性能将退化至少50%。
比传统的HashMap时间效率低。
因为其会对key从小到大排序,使用二分法查询key对应在数组中的下标。
在添加、删除、查找数据的时候都是先使用二分查找法得到相应的index,然后通过index来进行添加、查找、删除等操作。

所以其是按照key的大小排序存储的。

适用场景:

  • 数据量不大
  • 空间比时间重要
  • 需要使用Map
  • 在Android平台,相对来说,内存容量更宝贵。而且数据量不大。所以当需要使用keyObject类型的Map时,可以考虑使用ArrayMap来替换HashMap

示例代码:

        Map<String, String> map = new ArrayMap<>();map.put("1","1");map.put(null,"2");map.put("3",null);map.put("6",null);map.put("5",null);map.put("4",null);Log.d("TAG", "onCreate() called with: map = [" + map + "]");

输出:

 onCreate() called with: map = [{null=2, 1=1, 3=null, 4=null, 5=null, 6=null}]

3 构造函数

    //扩容默认的size, 4是相对效率较高的大小private static final int BASE_SIZE = 4;//表示集合是不可变的static final int[] EMPTY_IMMUTABLE_INTS = new int[0];//是否利用System.identityHashCode(key) 获取唯一HashCode模式。    final boolean mIdentityHashCode;//保存hash值的数组int[] mHashes;//保存key/value的数组。Object[] mArray;//容量int mSize;//创建一个空的ArrayMap,默认容量是0.当有Item被添加进来,会自动扩容public ArrayMap() {this(0, false);}//创建一个指定容量的ArrayMappublic ArrayMap(int capacity) {this(capacity, false);}//指定容量和identityHashCodepublic ArrayMap(int capacity, boolean identityHashCode) {mIdentityHashCode = identityHashCode;//数量<  0,构建一个不可变的ArrayMapif (capacity < 0) {mHashes = EMPTY_IMMUTABLE_INTS;mArray = EmptyArray.OBJECT;//数量= 0,构建空的mHashes mArray} else if (capacity == 0) {mHashes = EmptyArray.INT;mArray = EmptyArray.OBJECT;} else {//数量>0,分配空间初始化数组allocArrays(capacity);}mSize = 0;}//扩容private void allocArrays(final int size) {//数量<  0,构建一个不可变的ArrayMapif (mHashes == EMPTY_IMMUTABLE_INTS) {throw new UnsupportedOperationException("ArrayMap is immutable");}//扩容数量是 8if (size == (BASE_SIZE*2)) {synchronized (ArrayMap.class) {//查看之前是否有缓存的 容量为8的int[]数组和容量为16的object[]数组 //如果有,复用给mArray mHashesif (mTwiceBaseCache != null) {final Object[] array = mTwiceBaseCache;mArray = array;mTwiceBaseCache = (Object[])array[0];mHashes = (int[])array[1];array[0] = array[1] = null;mTwiceBaseCacheSize--;if (DEBUG) Log.d(TAG, "Retrieving 2x cache " + mHashes+ " now have " + mTwiceBaseCacheSize + " entries");return;}}} else if (size == BASE_SIZE) {//扩容数量是4synchronized (ArrayMap.class) {//查看之前是否有缓存的 容量为4的int[]数组和容量为8的object[]数组 //如果有,复用给mArray mHashesif (mBaseCache != null) {final Object[] array = mBaseCache;mArray = array;mBaseCache = (Object[])array[0];mHashes = (int[])array[1];array[0] = array[1] = null;mBaseCacheSize--;if (DEBUG) Log.d(TAG, "Retrieving 1x cache " + mHashes+ " now have " + mBaseCacheSize + " entries");return;}}}//构建mHashes和mArray,mArray是mHashes的两倍。因为它既要存key还要存value。mHashes = new int[size];mArray = new Object[size<<1];}//利用另一个map构建ArrayMappublic ArrayMap(ArrayMap<K, V> map) {this();if (map != null) {putAll(map);}}//批量put方法:public void putAll(ArrayMap<? extends K, ? extends V> array) {final int N = array.mSize;//确保空间足够存放ensureCapacity(mSize + N);//如果当前是空集合,if (mSize == 0) {if (N > 0) {//则直接复制覆盖数组内容即可。System.arraycopy(array.mHashes, 0, mHashes, 0, N);System.arraycopy(array.mArray, 0, mArray, 0, N<<1);mSize = N;}} else {//否则需要一个一个执行插入put操作for (int i=0; i<N; i++) {put(array.keyAt(i), array.valueAt(i));}}}//确保空间足够存放 minimumCapacity 个数据public void ensureCapacity(int minimumCapacity) {//如果不够扩容if (mHashes.length < minimumCapacity) {//暂存当前的hash array。后面复制需要final int[] ohashes = mHashes;final Object[] oarray = mArray;//扩容空间(开头讲过这个函数)allocArrays(minimumCapacity);if (mSize > 0) {//如果原集合不为空,复制原数据到新数组中System.arraycopy(ohashes, 0, mHashes, 0, mSize);System.arraycopy(oarray, 0, mArray, 0, mSize<<1);}//释放回收临时暂存数组空间freeArrays(ohashes, oarray, mSize);}}//释放回收临时暂存数组空间private static void freeArrays(final int[] hashes, final Object[] array, final int size) {//如果容量是8, 则将hashes 和array 缓存起来,以便下次使用if (hashes.length == (BASE_SIZE*2)) {synchronized (ArrayMap.class) {if (mTwiceBaseCacheSize < CACHE_SIZE) {//0存,前一个缓存的cachearray[0] = mTwiceBaseCache;//1 存 int[]数组array[1] = hashes;//2+ 元素置空 以便GCfor (int i=(size<<1)-1; i>=2; i--) {array[i] = null;}//更新缓存引用为arraymTwiceBaseCache = array;//增加缓存过的Array的数量mTwiceBaseCacheSize++;if (DEBUG) Log.d(TAG, "Storing 2x cache " + array+ " now have " + mTwiceBaseCacheSize + " entries");}}//相同逻辑,只不过缓存的是int[] 容量为4的数组 } else if (hashes.length == BASE_SIZE) {synchronized (ArrayMap.class) {if (mBaseCacheSize < CACHE_SIZE) {array[0] = mBaseCache;array[1] = hashes;for (int i=(size<<1)-1; i>=2; i--) {array[i] = null;}mBaseCache = array;mBaseCacheSize++;if (DEBUG) Log.d(TAG, "Storing 1x cache " + array+ " now have " + mBaseCacheSize + " entries");}}}}

小结:
* 扩容时,会查看之前是否有缓存的 int[]数组和object[]数组
* 如果有,复用给mArray mHashes

4 增 、改

4.1 单个增改 put(K key, V value)

    //如果key存在,则返回oldValuepublic V put(K key, V value) {//key的hash值final int hash;//下标int index;// 如果key为null,则hash值为0.if (key == null) {hash = 0;//寻找null的下标index = indexOfNull();} else {//根据mIdentityHashCode 取到 hash值hash = mIdentityHashCode ? System.identityHashCode(key) : key.hashCode();//根据hash值和key 找到合适的indexindex = indexOf(key, hash);}//如果index>=0,说明是替换(改)操作if (index >= 0) {//只需要更新value 不需要更新key。因为key已经存在index = (index<<1) + 1;//返回旧值final V old = (V)mArray[index];mArray[index] = value;return old;}//index<0,说明是插入操作。 对其取反,得到应该插入的下标index = ~index;//如果需要扩容if (mSize >= mHashes.length) {//如果容量大于8,则扩容一半。//否则容量大于4,则扩容到8.//否则扩容到4final int n = mSize >= (BASE_SIZE*2) ? (mSize+(mSize>>1)): (mSize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE);//临时数组final int[] ohashes = mHashes;final Object[] oarray = mArray;//分配空间完成扩容allocArrays(n);//复制临时数组中的数组进新数组if (mHashes.length > 0) {if (DEBUG) Log.d(TAG, "put: copy 0-" + mSize + " to 0");System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);System.arraycopy(oarray, 0, mArray, 0, oarray.length);}//释放临时数组空间freeArrays(ohashes, oarray, mSize);}//如果index在中间,则需要移动数组,腾出中间的位置if (index < mSize) {if (DEBUG) Log.d(TAG, "put: move " + index + "-" + (mSize-index)+ " to " + (index+1));System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index);System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1);}//hash数组,就按照下标存哈希值mHashes[index] = hash;//array数组,根据下标,乘以2存key,乘以2+1 存valuemArray[index<<1] = key;mArray[(index<<1)+1] = value;mSize++;//修改sizereturn null;}//返回key为null的 下标indexint indexOfNull() {//N为当前集合size final int N = mSize;//如果当前集合是空的,返回~0if (N == 0) {//return ~0;}//根据hash值=0,通过二分查找,查找到目标indexint index = ContainerHelpers.binarySearch(mHashes, N, 0);//如果index《0,则hash值=0之前没有存储过数据if (index < 0) {return index;}//如果index>=0,说明该hash值,之前存储过数据,找到对应的key,比对key是否等于null。相等的话,返回index。说明要替换。  //关于array中对应数据的位置,是index*2 = key ,index*2+1 = value.if (null == mArray[index<<1]) {return index;}//以下两个for循环是在出现hash冲突的情况下,找到正确的index的过程://从index+1,遍历到数组末尾,找到hash值相等,且key相等的位置,返回int end;for (end = index + 1; end < N && mHashes[end] == 0; end++) {if (null == mArray[end << 1]) return end;}//从index-1,遍历到数组头,找到hash值相等,且key相等的位置,返回for (int i = index - 1; i >= 0 && mHashes[i] == 0; i--) {if (null == mArray[i << 1]) return i;}// key没有找到,返回一个负数。代表应该插入的位置return ~end;}//根据key和key的hash值,返回indexint indexOf(Object key, int hash) {//N为当前集合size final int N = mSize;//如果当前集合是空的,返回~0if (N == 0) {return ~0;}//根据hash值,通过二分查找,查找到目标indexint index = ContainerHelpers.binarySearch(mHashes, N, hash);//如果index《0,说明该hash值之前没有存储过数据if (index < 0) {return index;}//如果index>=0,说明该hash值,之前存储过数据,找到对应的key,比对key是否相等。相等的话,返回index。说明要替换。if (key.equals(mArray[index<<1])) {return index;}//以下两个for循环是在出现hash冲突的情况下,找到正确的index的过程://从index+1,遍历到数组末尾,找到hash值相等,且key相等的位置,返回int end;for (end = index + 1; end < N && mHashes[end] == hash; end++) {if (key.equals(mArray[end << 1])) return end;}//从index-1,遍历到数组头,找到hash值相等,且key相等的位置,返回for (int i = index - 1; i >= 0 && mHashes[i] == hash; i--) {if (key.equals(mArray[i << 1])) return i;}// key没有找到,返回一个负数。代表应该插入的位置return ~end;}

4.2 批量增 putAll(Map

    //批量增,接受更为广泛的Map参数public void putAll(Map<? extends K, ? extends V> map) {//确保空间容量足够ensureCapacity(mSize + map.size());for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {//分别调用单个增方法 addput(entry.getKey(), entry.getValue());}}

小结:
* 增的流程:1 先根据key得到hash值,2 根据hash值得到index 3 根据index正负,得知是插入还是替换 4 如果是替换直接替换值即可 5 如果是插入,则先判断是否需要扩容,并进行扩容 6 挪动数组位置,插入元素(类似ArrayList)

  • 插入允许key为null,value为null。
  • 每次插入时,根据key的哈希值,利用二分查找,去寻找key在int[] mHashes数组中的下标位置。
  • 如果出现了hash冲突,则从需要从目标点向两头遍历,找到正确的index。
  • 如果index>=0,说明之前已经存在该key,需要替换(改)。
  • 如果index<0,说明没有找到。(也是二分法特性)对index去反,可以得到这个index应该插入的位置。
  • 根据keyhash值在mHashs中的index,如何得到key、valuemArray中的下标位置呢?key的位置是index*2value的位置是index*2+1,也就是说mArray是利用连续的两位空间去存放key、value
  • 根据hash值的index计算,key、valueindex也利用了位运算。index<<1 和 (index<<1)+1

5 删

5.1 单个删

    //如果对应key有元素存在,返回value。否则返回nullpublic V remove(Object key) {//根据key,找到下标final int index = indexOfKey(key);if (index >= 0) {//如果index>=0,说明key有对应的元素存在,则去根据下标删除return removeAt(index);}//否则返回nullreturn null;}
    //根据下标删除元素public V removeAt(int index) {//根据index,得到valuefinal Object old = mArray[(index << 1) + 1];//如果之前的集合长度小于等于1,则执行过删除操作后,集合现在就是空的了if (mSize <= 1) {// Now empty.if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to 0");//释放回收空间freeArrays(mHashes, mArray, mSize);//置空mHashes = EmptyArray.INT;mArray = EmptyArray.OBJECT;mSize = 0;} else {//根据元素数量和集合占用的空间情况,判断是否要执行收缩操作//如果 mHashes长度大于8,且 集合长度 小于当前空间的 1/3,则执行一个 shrunk,收缩操作,避免空间的浪费if (mHashes.length > (BASE_SIZE*2) && mSize < mHashes.length/3) {// Shrunk enough to reduce size of arrays.  We dont allow it to// shrink smaller than (BASE_SIZE*2) to avoid flapping between// that and BASE_SIZE.//如果当前集合长度大于8,则n为当前集合长度的1.5倍。否则n为8.//n 为收缩后的 mHashes长度final int n = mSize > (BASE_SIZE*2) ? (mSize + (mSize>>1)) : (BASE_SIZE*2);if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to " + n);//分配新的更小的空间(收缩操作)final int[] ohashes = mHashes;final Object[] oarray = mArray;allocArrays(n);//删掉一个元素,所以修改集合元素数量mSize--;//因为执行了收缩操作,所以要将老数据复制到新数组中。if (index > 0) {if (DEBUG) Log.d(TAG, "remove: copy from 0-" + index + " to 0");System.arraycopy(ohashes, 0, mHashes, 0, index);System.arraycopy(oarray, 0, mArray, 0, index << 1);}//在复制的过程中,排除不复制当前要删除的元素即可。if (index < mSize) {if (DEBUG) Log.d(TAG, "remove: copy from " + (index+1) + "-" + mSize+ " to " + index);System.arraycopy(ohashes, index + 1, mHashes, index, mSize - index);System.arraycopy(oarray, (index + 1) << 1, mArray, index << 1,(mSize - index) << 1);}} else {//不需要收缩//修改集合长度mSize--;//类似ArrayList,用复制操作去覆盖元素达到删除的目的。if (index < mSize) {if (DEBUG) Log.d(TAG, "remove: move " + (index+1) + "-" + mSize+ " to " + index);System.arraycopy(mHashes, index + 1, mHashes, index, mSize - index);System.arraycopy(mArray, (index + 1) << 1, mArray, index << 1,(mSize - index) << 1);}//记得置空,以防内存泄漏mArray[mSize << 1] = null;mArray[(mSize << 1) + 1] = null;}}//返回删除的值return (V)old;}

5.2 批量删除

    //从ArrayMap中,删除Collection集合中,所有出现的key。//返回值代表是否成功删除元素public boolean removeAll(Collection<?> collection) {return MapCollections.removeAllHelper(this, collection);}//MapCollections.removeAllHelper(this, collection);//遍历Collection,调用Map.remove(key)去删除元素;public static <K, V> boolean removeAllHelper(Map<K, V> map, Collection<?> collection) {int oldSize = map.size();Iterator<?> it = collection.iterator();while (it.hasNext()) {map.remove(it.next());}//如果元素不等,说明成功删除元素return oldSize != map.size();}
  • 根据元素数量和集合占用的空间情况,判断是否要执行收缩操作
  • 类似ArrayList,用复制操作覆盖元素达到删除的目的。

6 查

当你想获取某个value的时候,ArrayMap会计算输入key转换过后的hash值,然后对hash数组使用二分查找法寻找到对应的index,然后我们可以通过这个index在另外一个数组中直接访问到需要的键值对。如果在第二个数组键值对中的key和前面输入的查询key不一致,那么就认为是发生了碰撞冲突。为了解决这个问题,我们会以该key为中心点,分别上下展开,逐个去对比查找,直到找到匹配的值。如下图所示:


随着数组中的对象越来越多,查找访问单个对象的花费也会跟着增长,这是在内存占用与访问时间之间做权衡交换。

6.1 单个查

    public V get(Object key) {//根据key去得到indexfinal int index = indexOfKey(key);//根据 index*2+1 得到valuereturn index >= 0 ? (V)mArray[(index<<1)+1] : null;}public int indexOfKey(Object key) {//判断key是否是null,并去查询key对应的indexreturn key == null ? indexOfNull(): indexOf(key, mIdentityHashCode ? System.identityHashCode(key) : key.hashCode());}

总结

ArrayMap的实现细节很多地方和ArrayList很像,由于我们之前分析过面试必备:ArrayList源码解析(JDK8)。所以对于用数组复制覆盖去完成删除等操作的细节,就比较容易理解了。

  • 每次插入时,根据key的哈希值,利用二分查找,去寻找key在int[] mHashes数组中的下标位置。
  • 如果出现了hash冲突,则从需要从目标点向两头遍历,找到正确的index。
  • 扩容时,会查看之前是否有缓存的 int[]数组和object[]数组
  • 如果有,复用给mArray mHashes
  • 扩容规则:如果容量大于8,则扩容一半。(类似ArrayList)
  • 根据keyhash值在mHashs中的index,如何得到key、valuemArray中的下标位置呢?key的位置是index*2value的位置是index*2+1,也就是说mArray是利用连续的两位空间去存放key、value
  • 根据元素数量和集合占用的空间情况,判断是否要执行收缩操作
  • 如果 mHashes长度大于8,且 集合长度 小于当前空间的 1/3,则执行一个 shrunk,收缩操作,避免空间的浪费
  • 类似ArrayList,用复制操作覆盖元素达到删除的目的。

面试必备:ArrayMap源码解析相关推荐

  1. Android技术栈--HashMap和ArrayMap源码解析

    1 总览 WARNING!!:本文字数较多,内容较为完整并且部分内容难度较大,阅读本文需要较长时间,建议读者分段并耐心阅读. 本文会对 Android 中常用的数据结构进行源码解析,包括 HashMa ...

  2. Android技术栈(五)HashMap(包括红黑树)与ArrayMap源码解析

    1 总览 本文会对 Android 中常用HashMap(有红黑树)和ArrayMap进行源码解析,其中 HashMap 源码来自 Android Framework API 28 (JDK=1.8) ...

  3. Android特别的数据结构(二)ArrayMap源码解析

    1. 数据结构 public final class ArrayMap<K,V> implements Map<K,V> 由两个数组组成,一个int[] mHashes用来存放 ...

  4. 不再害怕面试问ArrayMap一文完全看懂Android ArrayMap源码解析

    作者:VIjolie 前言 ArrayMap是谷歌推出的在安卓等设备上用于替代HashMap的数据结构,和HashMap相比,具有更高的内存使用率,因此适合在Android等内存较为紧张的移动设备,下 ...

  5. ArrayMap 源码解析

    1.简述 我们都知道 HashMap,它属于 java.util 包下,但是很多人可能对 ArrayMap 并不是很熟悉,通俗来说 ArrayMap 属于 android.util 包下,是用于 An ...

  6. Android ArrayMap源码解析

    数据结构: int[] mHashes;Object[] mArray; 为两个数组实现,mHashes 负责记录Key的hash,key的hash所在的位置index,在mArray对应的位置 in ...

  7. ArrayMap 源码的详细解析

    最近在写framework层的系统服务,发现Android 12中用来去重注册监听的map都是用的ArrayMap,因此仔细研究了ArrayMap的原理. 目录 一. ArrayMap概述 二. Ar ...

  8. ArrayMap 源码分析

    文章目录 概述 主要属性 构造方法 put indexOfNull() indexOf remove get 参考 概述 ArrayMap 是 Android 的 API,它和 Java 的 Hash ...

  9. 面试必备:LinkedHashMap源码解析(JDK8)

    1 概述 在上文中,我们已经聊过了HashMap,本篇是基于上文的基础之上.所以如果没看过上文,请先阅读面试必备:HashMap源码解析(JDK8)  本文将从几个常用方法下手,来阅读LinkedHa ...

最新文章

  1. ProE官方网站系列视频教程
  2. python动态语言解释_python是动态语言吗
  3. 语义分析的一些方法(上篇)
  4. 苹果公司有“内鬼”!ID被盗后每条只卖10元钱
  5. TRIE - Data Structure
  6. Maven and Ant for Hybris
  7. oryx-editor 客户端的加载过程
  8. HTML、JS、字符串的简单加密与解密
  9. 95-20-060-启动器-Bootstrap
  10. Hadoop生态圈介绍
  11. HDOJ 2642 HDU 2642 Stars ACM 2642 IN HDU
  12. OC中的内省方法初探
  13. CentOS6.5 环境安装配置
  14. php 输出tab_php实现读取和写入tab分割的文件
  15. 前端页面预览word_html页面在线预览word
  16. Javaweb常用单词
  17. winSCP start
  18. 80老翁谈人生(314):别了,亲爱的CSDN读者朋友们!
  19. 关于相干解调中的同频同相问题
  20. android 充电模式deamon_Android Lint工作原理剖析

热门文章

  1. w7计算机u盘在哪里,win7电脑无法发现u盘怎么解决
  2. 测试成绩软件,软件部分测试成绩_精英 Z87H3-A3X_主板评测-中关村在线
  3. Python学习day2作业总结
  4. 这样的测试简历,面试官都喜欢
  5. 2021年大连12中高考成绩查询,2021年大连各高中高考成绩排名及放榜最新消息
  6. MySQL省市区自联表,拿走不谢!!!
  7. UE4 自建基础玩家时重力的设置
  8. WIN10 怎么关闭开机启动项
  9. Genexus 15 安卓SDK配置项
  10. Latex 图片及表格排列代码