I can think of several reasons why HashMap
s with integer keys are much better than SparseArray
s:
The android documentation for a SparseArray says "It is generally slower than a traditional HashMap".
Yes,it's right. But when you have only 10 or 20 items , the performance difference should be insignificant.
If you write code using HashMaps rather than SparseArrays your code will work with other implementations of Map and you will be able to use all of the java APIs designed for Maps
I think most often we only use HashMap
to search a value associated with a key while SparseArray
is really good at this.
If you write code using HashMaps rather than SparseArrays your code will work in non-android projects.
The source code of SparseArray is fairly simple and easy to understand so that you only pay little effort moving it to other platforms(through a simple COPY&Paste).
Map overrides equals() and hashCode() whereas SparseArray doesn't
All I can say is, (to most developers)who care?
Another important aspect of SparseArray
is that it only uses an array to store all elements while HashMap
uses Entry
, so SparseArray
costs significant less memory than a HashMap
, see this