我是在 android 中开发的新手。在我正在使用的 android 应用程序中HashMap
,但我收到警告:
**"Use new SparseArray<String>(...) instead for better performance"**
这是什么意思,我该如何使用SparseArray<String>
?
使用 new
SparseArray<String>(...)
代替以获得更好的性能
由于此处描述的原因,您会收到此警告。
SparseArrays 将整数映射到对象。与普通的对象数组不同,索引中可能存在间隙。它旨在比使用 HashMap 将整数映射到对象更有效。
现在
我如何使用 SparseArray ?
您可以通过以下方式做到这一点:
HashMap
方法:
Map<Integer, Bitmap> _bitmapCache = new HashMap<Integer, Bitmap>();
private void fillBitmapCache() {
_bitmapCache.put(R.drawable.icon, BitmapFactory.decodeResource(getResources(), R.drawable.icon));
_bitmapCache.put(R.drawable.abstrakt, BitmapFactory.decodeResource(getResources(), R.drawable.abstrakt));
_bitmapCache.put(R.drawable.wallpaper, BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper));
_bitmapCache.put(R.drawable.scissors, BitmapFactory.decodeResource(getResources(),
}
Bitmap bm = _bitmapCache.get(R.drawable.icon);
SparseArray
方法:
SparseArray<Bitmap> _bitmapCache = new SparseArray<Bitmap>();
private void fillBitmapCache() {
_bitmapCache.put(R.drawable.icon, BitmapFactory.decodeResource(getResources(), R.drawable.icon));
_bitmapCache.put(R.drawable.abstrakt, BitmapFactory.decodeResource(getResources(), R.drawable.abstrakt));
_bitmapCache.put(R.drawable.wallpaper, BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper));
_bitmapCache.put(R.drawable.scissors, BitmapFactory.decodeResource(getResources(),
}
Bitmap bm = _bitmapCache.get(R.drawable.icon);
希望它会有所帮助。
SparseArray
当您使用 anInteger
作为键时使用。
使用 时SparseArray
,键将始终保持为原始变量,这与使用时HashMap
需要将 aObject
作为键不同,这将导致int在短时间内成为Integer
对象,同时将对象放入地图。
通过使用,SparseArray
您将为垃圾收集器节省一些工作。
所以使用就像一个Map<Integer,String>
.
这暗示您的代码有更好的数据结构。
该提示来自 Lint。当你有一个HashMap
整数到别的东西时,你通常会得到它。
它最大的优点是将整数键视为原语。换句话说,它不会转换为Integer
(Java 对象)以将其用作键。
这在使用大地图时很重要。HashMap
在这种情况下,将导致创建很多很多Integer
对象。
在此处查看更多信息。
对于整数键值对,SparseArray 是比 HashMap 更好的内存效率数据结构。它是特定于 Android 的,我相信它不能用于 Java SE。
有时,Linter 警告显示 SparseArray 必须像上面那样使用。这个愚蠢的警告可能是对的,也可能是错的。如果您发现它合适,您需要决定使用 SparseArray 而不是 HashMap,或者您需要使用 @SuppressLint 注释来抑制它。
要决定是否实施,值得做一些研究并评估您的情况。你可以在这里找到所有有用的链接
https://gunhansancar.com/sparsearray-vs-hashmap/
https://developer.android.com/reference/android/util/SparseIntArray