Hashmap is a dictionary class, that store objects based on a key. Using a Hashmap, we can store an image represented by the android.graphics.Bitmap class by some key using the setImage method and later retrieve it using the same key using the getImage method as shown below:
import java.util.HashMap; import android.graphics.Bitmap; /** * The Class BitmapCache. */ public class BitmapCache { /** The cache. */ private static HashMap<String, Bitmap> cache = new HashMap<String, Bitmap>(); /** * Gets the image. * * @param key * the key * @return the image */ public static Bitmap getImage(String key) { if (cache.containsKey(key)) { return cache.get(key); } return null; } /** * Sets the image. * * @param key * the key * @param image * the image */ public static void setImage(String key, Bitmap image) { cache.put(key, image); } }
This cache be extended further to evict objects (bitmaps) based on time to live, or based on number of entries in cache etc.
Caching bitmaps will reduce CPU time and making the app more responsive. However each bitmap occupies a certain amount of memory depending on its resolution and image size,so the number of bitmaps cached at a given time should be limited based on the memory available in the device or else it would result in Out of Memory causing the application to crash.