Warning shows when i use Hash Map In android(Use new SparseArray<String>)
I am new to developing in android. In my android app I'm using HashMap
, but I'm getting a warning:
**"Use new SparseArray<String>(...) instead for better performance"**
What does this mean, and how can I use SparseArray<String>
instead?
Solution 1:
Use new
SparseArray<String>(...)
instead for better performance
You are getting this warning because of reason described here.
SparseArrays map integers to Objects. Unlike a normal array of Objects, there can be gaps in the indices. It is intended to be more efficient than using a HashMap to map Integers to Objects.
Now
how i use SparseArray ?
You can do it by below ways:
-
HashMap
way: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
way: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);
Hope it Will Help.
Solution 2:
SparseArray
is used when you are using an Integer
as a key.
When using the SparseArray
, the key will stay as a primitive variable at all times unlike when you use the HashMap
where it is required to have a Object
as a key which will cause the int to become an Integer
object just for a short time while getting the object in the map.
By using the SparseArray
you will save the Garbage Collector some work.
So use just like a Map<Integer,String>
.