table = newTab;

可以看到当我们的table数组存储的节点值大于threshold时,会按我们的当前数组大小的两倍生成一个新的数组,并把旧数组上的数据复制到新数组上这就是我们的HashMap扩容。伴随着一个新数组的生成和数组数据的copy,会有一定性能上的损耗。如果我们在使用HashMap的是能够明确HashMap能够一开始就清楚的知道HashMap存储的键值对个数,我建议我们使用HashMap的另一个构造方法。

public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); }

注意了这个initialCapacity值最好去2的整数次幂。如果我们要存放40个键值对,那我们这个initialCapacity最好传64。至于为什么这样,我们下次在去讨论。

下面我们来分析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)

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;

}

在get的时候,我们首先会根据我们的key去计算它的hash值,如果这个hash值不存在,我们直接反回null。

如果存在,在没有发生hash冲突的情况下也就是根据当前hash值计算出的索引上的存储数据不是以树和链表的形式存储的时候,我们直接返回当前索引上存储的值,如果时链表树,我们就去遍历节点上的数据通过equals去比对,找到我们需要的在返回。

通过上面我可以得出结论,当HashMap没有发生hash冲突时,hashMap的查找和插入的时间复杂度都是O(1),效率时非常高的。

当我们发生扩容和hash冲突时,会带来一定性能上的损耗。

HashMap大致分析完了。

下面我们来分析分析Android为我们提供的ArrayMap和SparseArray。

二.我们在来看看ArrayMap:


public class A
rrayMap<K, V> extends SimpleArrayMap<K, V> implements Map<K, V> {

MapCollections<K, V> mCollections;

int[] mHashes;

Object[] mArray;

通过源码我们可以看到ArrayMap继承自SimpleArrayMap实现了Map接口,ArrayMap内部是两个数组,一个存放hash值,一个存放Obeject对象也就是value值,这一点就和HashMap不一样了。我们现来看看ArrayMap的构造方法:

public ArrayMap(int capacity) {

super(capacity);

}

public SimpleArrayMap() {

mHashes = ContainerHelpers.EMPTY_INTS;

mArray = ContainerHelpers.EMPTY_OBJECTS;

mSize = 0;

}

我们发现ArrayMap的初始化会给我们初始化两个空数组,并不像HashMap一样为我们默认初始化了一个大小为16的table数组,下面我们继续往下看:

public V put(K key, V value) {

final int osize = mSize;

final int hash;

int index;

if (key == null) {

hash = 0;

index = indexOfNull();

} else {

hash = key.hashCode();

index = indexOf(key, hash);

}

if (index >= 0) {

index = (index<<1) + 1;

final V old = (V)mArray[index];

mArray[index] = value;

return old;

}

index = ~index;

if (osize >= mHashes.length) {

final int n = osize >= (BASE_SIZE*2) ? (osize+(osize>>1))
(osize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE);

if (DEBUG) Log.d(TAG, "put: grow from " + mHashes.length + " to " + n);

final int[] ohashes = mHashes;

final Object[] oarray = mArray;

allocArrays(n);

if (CONCURRENT_MODIFICATION_EXCEPTIONS && osize != mSize) {

throw new ConcurrentModificationException();

}

if (mHashes.length > 0) {

if (DEBUG) Log.d(TAG, “put: copy 0-” + osize + " to 0");

System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);

System.arraycopy(oarray, 0, mArray, 0, oarray.length);

}

freeArrays(ohashes, oarray, osize);

}

if (index < osize) {

if (DEBUG) Log.d(TAG, "put: move " + index + “-” + (osize-index)

  • " to " + (index+1));

System.arraycopy(mHashes, index, mHashes, index + 1, osize - index);

System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1);

}

if (CONCURRENT_MODIFICATION_EXCEPTIONS) {

if (osize != mSize || index >= mHashes.length) {

throw new ConcurrentModificationException();

}

}

mHashes[index] = hash;

mArray[index<<1] = key;

mArray[(index<<1)+1] = value;

mSize++;

return null;

}

我们先看看put方法的实现。首先就是判段key是否null,是null,hash值直接置为0,如果不为null,通过Obejct的hashCode()方法计算出hash值。然后通过indexfOf方法计算出index的值。下面我们来看看indexOf方法:

int indexOf(Object key, int hash) {

final int N = mSize;

// Important fast case: if nothing is in here, nothing to look for.

if (N == 0) {

return ~0;

}

int index = binarySearchHashes(mHashes, N, hash);

// If the hash code wasn’t found, then we have no entry for this key.

if (index < 0) {

return index;

}

// If the key at the returned index matches, that’s what we want.

if (key.equals(mArray[index<<1])) {

return index;

}

// Search for a matching key after the index.

int end;

for (end = index + 1; end < N && mHashes[end] == hash; end++) {

if (key.equals(mArray[end << 1])) return end;

}

// Search for a matching key before the index.

for (int i = index - 1; i >= 0 && mHashes[i] == hash; i–) {

if (key.equals(mArray[i << 1])) return i;

}

// Key not found – return negative value indicating where a

// new entry for this key should go. We use the end of the

// hash chain to reduce the number of array entries that will

// need to be copied when inserting.

return ~end;

}

我们可以看到indexOf方法内部是根据binarySearchHashes()去搜索hash值得,下面我们再来看看binarySearchHashes()

内部调用了ContainerHelpers.binarySearch(hashes, N, hash);我们在看来看看binarySearch方法。

static int binarySearch(int[] array, int size, int value) {

int lo = 0;

int hi = size - 1;

while (lo <= hi) {

int mid = (lo + hi) >>> 1;

int midVal = array[mid];

if (midVal < value) {

lo = mid + 1;

} else if (midVal > value) {

hi = mid - 1;

} else {

return mid; // value found

}

}

return ~lo; // value not present

}

可以发现binarySearch是典型得二叉搜索算法。所以我们可以得出结论,ArrayMap插入和索引是基于二叉搜索实现得。这种搜索得效率也很高,他的时间复杂度O(log(n)),但是和HashMap O(1)还是有点差距的。

下面我们继续看indexOf方法,如果我们通过二叉搜索查到得index值小于0,代表我们没有存储过该数据则直接返回,如果index大于0,我们就去通过equals去比对原来索引得上得key,如果相等,代表我们存储过该值,直接返回index,到时候我们存储的时候会直接覆盖掉当前已经存储得值。如果不相等,出现Hash冲突,重新计算出一个index值返回。

下面我们来看看ArrayMap如何处理Hash冲突和扩容的(我们没有指定容量的时候,ArrayMap默认初始化了两个空数组)。

if (osize >= mHashes.length)

出现hash冲突后,如果我们的存储数据数量大小已经大于等于我们的hash数组的大小。我们对数组进行扩容。

final int n = osize >= (BASE_SIZE*2) ? (osize+(osize>>1))
(osize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE);

if (mHashes.length > 0) {

if (DEBUG) Log.d(TAG, “put: copy 0-” + osize + " to 0");

System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);

System.arraycopy(oarray, 0, mArray, 0, oarray.length);

}

如果我们的osize(已经存储的多少value个数)大于等于两倍的BASE_SIZE(常量为4)我们就在原来osize的基础上扩容0.5倍,

如果我们的osize小于8(两个BASE_SIZE)并且大于4(一个BASE_SIZE),我们将数组扩容到8,否则我们将数组大小扩容到4。

根据上面的分析,我们可以得出结论,ArrayMap的插入和索引是基于二分法的。查找和索引效率不如HashMap。但是要比HashMap占用更少的内存空间,HashMap扩容实是在原来起table的基础上扩容一倍,而ArrayMap实在存储数据的个数上扩容0.5倍,不会造成太多的空间浪费。在移动设备上内存远比PC设备上值钱的多。ArrayMap的设计就是用时间换取空间。

三.SparseArray:


public SparseArray() {

this(10);

}

public SparseArray(int initialCapacity) {

if (initialCapacity == 0) {

mKeys = EmptyArray.INT;

mValues = EmptyArray.OBJECT;

} else {

mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);

mKeys = new int[mValues.length];

}

mSize = 0;

}

public void put(int key, E value) {

int i = ContainerHelpers.binarySearch(mKeys, mSize, key);

if (i >= 0) {

mValues[i] = value;

} else {

i = ~i;

if (i < mSize && mValues[i] == DELETED) {

mKeys[i] = key;

mValues[i] = value;

return;

}

if (mGarbage && mSize >= mKeys.length) {

gc();

Capacity == 0) {

mKeys = EmptyArray.INT;

mValues = EmptyArray.OBJECT;

} else {

mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);

mKeys = new int[mValues.length];

}

mSize = 0;

}

public void put(int key, E value) {

int i = ContainerHelpers.binarySearch(mKeys, mSize, key);

if (i >= 0) {

mValues[i] = value;

} else {

i = ~i;

if (i < mSize && mValues[i] == DELETED) {

mKeys[i] = key;

mValues[i] = value;

return;

}

if (mGarbage && mSize >= mKeys.length) {

gc();

HashMap,ArrayMap,SparseArray 源码角度分析,Android中的数据结构你该如何去选择?相关推荐

  1. 从源码角度分析Android中的Binder机制的前因后果

    为什么在Android中使用binder通信机制? 众所周知linux中的进程通信有很多种方式,比如说管道.消息队列.socket机制等.socket我们再熟悉不过了,然而其作为一款通用的接口,通信开 ...

  2. 从源码角度解析Android中APK安装过程

    从源码角度解析Android中APK的安装过程 1. Android中APK简介 Android应用Apk的安装有如下四种方式: 1.1 系统应用安装 没有安装界面,在开机时自动完成 1.2 网络下载 ...

  3. 带你从源码角度分析ViewGroup中事件分发流程

    序言 这篇博文不是对事件分发机制全面的介绍,只是从源码的角度分析ACTION_DOWN.ACTION_MOVE.ACTION_UP事件在ViewGroup中的分发逻辑,了解各个事件在ViewGroup ...

  4. 从源码角度分析Android系统的异常捕获机制是如何运行的

    我们在开发的时候经常会遇到各种异常,当程序遇到异常,便会将异常信息抛到LogCat中,那这个过程是怎么实现的呢? 我们以一个例子开始: import android.app.Activity; imp ...

  5. 【Android 插件化】Hook 插件化框架 ( 从源码角度分析加载资源流程 | Hook 点选择 | 资源冲突解决方案 )

    Android 插件化系列文章目录 [Android 插件化]插件化简介 ( 组件化与插件化 ) [Android 插件化]插件化原理 ( JVM 内存数据 | 类加载流程 ) [Android 插件 ...

  6. 从源码角度看Android系统SystemServer进程启动过程

    SystemServer进程是由Zygote进程fork生成,进程名为system_server,主要用于创建系统服务. 备注:本文将结合Android8.0的源码看SystemServer进程的启动 ...

  7. 从源码角度看Android系统Zygote进程启动过程

    在Android系统中,DVM.ART.应用程序进程和SystemServer进程都是由Zygote进程创建的,因此Zygote又称为"孵化器".它是通过fork的形式来创建应用程 ...

  8. Mybatis底层原理学习(二):从源码角度分析一次查询操作过程

    在阅读这篇文章之前,建议先阅读一下我之前写的两篇文章,对理解这篇文章很有帮助,特别是Mybatis新手: 写给mybatis小白的入门指南 mybatis底层原理学习(一):SqlSessionFac ...

  9. 从源码角度看Android系统Launcher在开机时的启动过程

    Launcher是Android所有应用的入口,用来显示系统中已经安装的应用程序图标. Launcher本身也是一个App,一个提供桌面显示的App,但它与普通App有如下不同: Launcher是所 ...

最新文章

  1. Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办?
  2. Spark RDD/Core 编程 API入门系列之动手实战和调试Spark文件操作、动手实战操作搜狗日志文件、搜狗日志文件深入实战(二)...
  3. GDCM:png文件转为dcm文件的测试程序
  4. 整型变量(int)与字节数组(byte[])的相互转换
  5. mysql数据库连接失败,挑战大厂重燃激情!
  6. 在.NET3.5平台上使用LinQ to SQL + NBear 创建三层WEB应用
  7. 机器学习竞赛中,为什么GBDT往往比深度学习更有效?
  8. 最新版飞鸽传书(http://www.freeeim.com)下载
  9. 【NGS接龙】薛宇:漫谈生物信息圈儿的那些年、那些事!
  10. Quality of Service 0, 1 2
  11. 游戏程序中的骨骼插件
  12. 开课吧:数据分析能够给企业带来什么价值?
  13. 设置 phpstorm 左侧文件自动定位到当前编辑的文件
  14. 2016计算机二级java_2016年计算机二级《JAVA》考试练习题
  15. 如何看待职场猝死?燕麦企业云盘教你9大绝招提升职场幸福感
  16. Win11系统设置自动关机的方法分享
  17. 如何撰写搜索引擎广告创意
  18. 1t硬盘怎么分区最好_1TB的硬盘如何分区比较合理?
  19. 3D俯视角色割草游戏模板+视频教程,免费发布 | 一周精品推荐
  20. HTML5游戏开发引擎

热门文章

  1. Unreal Engin_画廊制作笔记 _007Fog处理,雾的设置
  2. Unreal Engin_画廊制作笔记 _008灯光处理,夜晚的画廊灯光设置
  3. kail里面的美杜莎和九头蛇的利用
  4. Web字体格式介绍及浏览器兼容性一览
  5. 探索艾利特机器人|EC66机器人在生猪疫苗注射中的应用
  6. HTML之表格,表单的使用
  7. Hexo+Github博客搭建之Matery主题个性化修改篇(一)
  8. 金庸武功之““兰花拂穴手””--elk5.5安装
  9. RayScan漏扫工具
  10. 如何用大数据进行甜品店选址要素分析