Let’s see in detail.
What is SparseArray?
It is a normal array of the objects that can map integer (Primitives) to value the objects.
What is HashMap?
It is an associative array of the objects that can map keys (Object) to value the objects.
Difference between SparseArray and HashMap
SparseArray | HashMap |
Avoids Auto boxing and Auto Unboxing |
If the keys are provided as primitive, then it does Auto Boxing and Auto Unboxing. |
Uses less memory. |
Uses more memory than SparseArray. |
Elements are searched, using Binary Search. |
Search will happen traversing every element in the list. |
Insert and delete of element is costlier because it rearranges all the elements afterwards. |
Insert and delete is easier because it just replaces address of the next elements like Linked List. |
Only available for Android. |
Also available in Java. |
When you should use SparseArray?
For smaller arrays (under 100), the performance difference is not significant, less than 50 percent.
For arrays larger than 100, if you are adding more than retrieving elements, try SparseArray.
For arrays larger than 100, I think you should use HashMap and ignore IntelliJ warning.