Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SparseArray with String key?

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?

like image 523
Mike6679 Avatar asked Jul 19 '14 04:07

Mike6679


People also ask

What is the difference between ArrayMap vs HashMap?

ArrayMap is a generic key -> value mapping data structure that is designed to be more memory efficient than a traditional HashMap. ArrayMap keeps its mappings in an array data structure — an integer array of hash codes for each item, and an Object array of the key -> value pairs.

What is SparseArray in Android?

SparseArray maps integers to Objects and, unlike a normal array of Objects, its indices can contain gaps. SparseArray is intended to be more memory-efficient than a HashMap , because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping.


1 Answers

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.

like image 170
Gabe Sechan Avatar answered Sep 20 '22 12:09

Gabe Sechan