Use SparseArray Instead of Map with Integer Keys

ID

java.android_sparse_arrays

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

android, best-practice, efficiency

Description

Reports declarations of Map<Integer, V>, HashMap<Integer, V>, TreeMap<Integer, V>, LinkedHashMap<Integer, V>, or ConcurrentHashMap<Integer, V> that could be replaced with Android’s SparseArray<V>. The SparseArray family avoids autoboxing the key and uses a more compact memory layout.

Rationale

A HashMap<Integer, V> autoboxes every int key into an Integer object, requiring an additional 16-byte object header per entry. Android’s SparseArray stores keys as primitive int values in a sorted array, saving memory and reducing GC pressure.

// Bad: Integer keys cause autoboxing
Map<Integer, Bitmap> cache = new HashMap<Integer, Bitmap>();

Remediation

Replace the map with the appropriate SparseArray variant: SparseArray<V> for general use, SparseBooleanArray for boolean values, SparseIntArray for int values, or SparseLongArray for long values.

// Good: no autoboxing, lower memory footprint
SparseArray<Bitmap> cache = new SparseArray<Bitmap>();