本文借鉴自文章Android中你还在用HashMap<Integer,Object>吗?
在Android Studio中输入以下代码:
Map<Integer,Object> map = new HashMap<>();
系统会提示:
Use new SparseArray<Object>(...) instead for better performance
推荐我们使用SparseArray<Object>
来取代HashMap<Integer,Object>
,以获取更好的性能。
SparseArray简介
SparseArray
是java.util
包下的类,介绍如下:
SparseArrays map integers to Objects. Unlike a normal array of Objects, there can be gaps in the indices. It is intended to be more memory efficient than using a HashMap to map Integers to Objects, both because it avoids auto-boxing keys and its data structure doesn’t rely on an extra entry object for each mapping.
大致意思是:
SparseArrays是个整型到对象的映射,与一般的对象数组不同,它的索引值可以为空。它设计的目的是为了比HashMap<Integer,Object>拥有更高的内存性能。
主要优点有两个:1. 它避免了对key自动装箱的操作;
2. 它的映射关系并不依赖于额外的对象;
简单提一下自动装箱:Integer i = 6;
将int基本数据类型的值包装成Integer类的对象,底层实际上调用Integer的构造函数,将int类型的值作为参数传入。
可能有人会有疑惑:为什么HashMap中的key是Integer类型而不是int类型,我们平常写入的基本上都是int类型的,这样还要自动装箱不是浪费吗?
这要从HashMap的原理来看,HashMap是通过key的hashcode值初步定位,而基本数据类型由于只能存放在栈空间中,没有对象可言,因而也没有hashCode()等方法,所以需要自动装箱成Integer类型,调用Integer类的hashCode()方法来获取hashcode值,这样不可避免地造成了性能的浪费。
这就对SparseArray提出了考验,怎样能够避免自动装箱造成的浪费同时又能够读写映射关系呢?
SparseArray的使用
我们先来对比一下SparseArray和HashMap的使用,代码如下:
//定义
SparseArray<Object> sparseArray = new SparseArray<>() ;
Map<Integer,Object> map = new HashMap<>() ;
//添加数据
sparseArray.put(1,new Object());
map.put(1,new Object()) ;
//取数据
Object o1 = sparseArray.get(