Amit Prajapati Amit Prajapati - 3 months ago 51
Android Question

Difference between SparseArray Vs ArrayList?

i want to know performance and efficency between SparseArray and ArrayList and which one is better to use.
i can't undestand when to use SparseArray and when ArrayList

Answer

The purpose of a SparseArray is to save memory if you have a list that has lots of gaps in. If you only have 10 items, and the numbers that index them range from 0 to 1000, then an ArrayList will have lots of null entries in it, and that will be quite wasteful. A SparseArray will use data structures internally to avoid that problem.

The alternative in this situation is a HashMap, which is better than a SparseArray if you have lots of items.

The implementation is not intended to be appropriate for data structures that may contain large numbers of items. It is generally slower than a traditional HashMap, since lookups require a binary search and adds and removes require inserting and deleting entries in the array. For containers holding up to hundreds of items, the performance difference is not significant, less than 50%.

From the Android dev documentation.