SparseArray vs HashMap

I can think of several reasons why HashMaps with integer keys are much better than SparseArrays:

  1. The Android documentation for a SparseArray says “It is generally slower than a traditional HashMap“.
  2. 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.
  3. If you write code using HashMaps rather than SparseArrays your code will work in non-android projects.
  4. Map overrides equals() and hashCode() whereas SparseArray doesn’t.

Yet whenever I try to use a HashMap with integer keys in an Android project, IntelliJ tells me I should use a SparseArray instead. I find this really difficult to understand. Does anyone know any compelling reasons for using SparseArrays?

7 Answers
7

Leave a Comment