When to use SparseArray vs HashMap?

Technology CommunityCategory: AndroidWhen to use SparseArray vs HashMap?
VietMX Staff asked 3 years ago

SparseArray can be used to replace HashMap when the key is a primitive type. A Sparse array in Java is a data structure which maps keys to values. Same idea as a Map, but different implementation:

A Sparse Array is simply made of two arrays: an arrays of (primitives) keys and an array of (objects) values. There can be gaps in these arrays indices, hence the term “sparse” array.

class SparseIntArray {
    int[] keys;
    int[] values;
    int size;
}

The main interest of the SparseArray is that it saves memory by using primitives instead of objects as the key.

Benefits are:

  • Allocation-free
  • No boxing

Drawbacks:

  • Generally slower, not indicated for large collections
  • They won’t work in a non-Android project

HashMap can be replaced by the following:

SparseArray          <Integer, Object>
SparseBooleanArray   <Integer, Boolean>
SparseIntArray       <Integer, Integer>
SparseLongArray      <Integer, Long>
LongSparseArray      <Long, Object>
LongSparseLongArray  <Long, Long>   //this is not a public class                                 
                                    //but can be copied from  Android source code