Android SparseArray with String key?

Mike6679 picture Mike6679 · Jul 19, 2014 · Viewed 11.7k times · Source

I need to use a hashmap to store key / values in my Android app (potentially thousands), but I understand that I should be using SparseArray in order to save memory. However, my key needs to be a String. Is there a way to create a custom implementation of the SparseArray or some other alternative?

Answer

Gabe Sechan picture Gabe Sechan · Jul 19, 2014

SparseArray is only a thing when integers are the key. It's a memory optimization that's only possible with integer values because you need to binary search the keys. Binary searches on strings are expensive and not well defined (should '1' be less than or greater than 'a' or 'crazy japanese character'?), so they don't do it.

BTW, SparseArray saves memory but may take more time. A get on a HashMap should be O(n/size) where size is the number of buckets in the hashmap. SparseArray is going to be O(log(n)). Which to use depends on memory and speed you need. If you have a truly large (100Ks of entries) you'll even run into memory paging issues where the physical realities of cache misses may cause the more HashMap to perform better even if its technically worse, because it will have a max of 1 cache miss per get, while a binary search may have multiple.