SparseArray instead HashMap Android example

Old code with 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);

Lint warning:
Use new SparseArray(…) instead for better performance
Issue: Looks for opportunities to replace HashMaps with the more efficient SparseArray
Id: UseSparseArrays

New code with 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 methods:
http://developer.android.com/reference/android/util/SparseArray.html

This entry was posted in Android Examples Code, Array,List,Collections and tagged , . Bookmark the permalink.


Comments are closed.

29,176 views