I can think of several reasons why HashMaps with integer keys are much better than SparseArrays:
I came here just wanting an example of how to use SparseArray. This is a supplemental answer for that.
SparseArray sparseArray = new SparseArray<>();
A SparseArray maps integers to some Object, so you could replace String in the example above with any other Object. If you are mapping integers to integers then use SparseIntArray.
Use put (or append) to add elements to the array.
sparseArray.put(10, "horse");
sparseArray.put(3, "cow");
sparseArray.put(1, "camel");
sparseArray.put(99, "sheep");
sparseArray.put(30, "goat");
sparseArray.put(17, "pig");
Note that the int keys do not need to be in order. This can also be used to change the value at a particular int key.
Use remove (or delete) to remove elements from the array.
sparseArray.remove(17); // "pig" removed
The int parameter is the integer key.
Use get to get the value for some integer key.
String someAnimal = sparseArray.get(99); // "sheep"
String anotherAnimal = sparseArray.get(200); // null
You can use get(int key, E valueIfKeyNotFound) if you want to avoid getting null for missing keys.
You can use keyAt and valueAt some index to loop through the collection because the SparseArray maintains a separate index distinct from the int keys.
int size = sparseArray.size();
for (int i = 0; i < size; i++) {
int key = sparseArray.keyAt(i);
String value = sparseArray.valueAt(i);
Log.i("TAG", "key: " + key + " value: " + value);
}
// key: 1 value: camel
// key: 3 value: cow
// key: 10 value: horse
// key: 30 value: goat
// key: 99 value: sheep
Note that the keys are ordered in ascending value, not in the order that they were added.