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?
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.
You can use ArrayMap : ArrayMap is a generic key->value mapping data structure that is designed to be more memory efficient than a traditional HashMap
For more information : ArrayMap Doc
You can use the hashCode of string -> mystring.hashCode()
SparseArray
is a specialized class for maps that have integers as the key type. They basically use that fact to save the int value instead of a reference to an Integer object (hence the memory savings).
There is nothing inherently wrong with using a standardHashMap
when the key is of any other type.
© 2022 - 2024 — McMap. All rights reserved.