SparseArray
HashMap
Data Structures
Android Development
Memory Optimization

SparseArray vs HashMap

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

On Android, SparseArray and HashMap can both store key-value pairs, but they solve slightly different problems. The most important difference is that SparseArray is optimized for integer keys and avoids boxing them into Integer objects, which usually saves memory and reduces object churn compared with HashMap<Integer, T>.

Why SparseArray exists

A HashMap<Integer, T> stores boxed Integer keys plus the hash table structure itself. On memory-sensitive Android code, especially older devices or UI-heavy paths, that overhead can matter.

SparseArray<T> avoids the Integer wrappers and stores keys and values in parallel arrays. That is why it often uses less memory for mappings keyed by int.

java
1SparseArray<String> names = new SparseArray<>();
2names.put(10, "Alice");
3names.put(42, "Bob");
4
5System.out.println(names.get(42));

The equivalent HashMap<Integer, String> is more general, but it pays for that generality.

Performance is not just about big-O labels

People often repeat that HashMap is O(1) and SparseArray is slower because it uses array search. That is directionally true, but incomplete.

In real Android apps, constant factors and allocation behavior matter. SparseArray can be very competitive for small to medium maps because:

  • it avoids boxing int keys
  • it creates fewer helper objects
  • it has a compact memory layout

For very large collections with heavy random access and updates, HashMap may win more clearly on lookup and mutation cost. For many Android UI cases, the memory savings of SparseArray are the main reason to choose it.

Choose based on key type first

If your keys are int, SparseArray is worth considering. If your keys are objects such as String, UUID, or custom classes, HashMap is the normal choice because SparseArray is not designed for those key types.

java
1HashMap<String, Integer> scores = new HashMap<>();
2scores.put("alice", 10);
3scores.put("bob", 20);
4
5System.out.println(scores.get("alice"));

So the decision is not really SparseArray versus every possible map. It is usually SparseArray<T> versus HashMap<Integer, T>.

SparseArray fits Android-specific patterns well

Android APIs often deal with resource IDs, adapter positions, view IDs, or other integer-indexed associations. Those are natural SparseArray use cases.

Examples include:

  • caching views by integer ID
  • storing controller objects keyed by numeric handles
  • mapping adapter positions to temporary state

For those cases, the Android-specific structure is often a better semantic fit than a generic Java map.

There are specialized sparse variants too

Android also provides related classes such as:

  • 'SparseIntArray for int to int'
  • 'LongSparseArray for long keys'
  • 'SparseBooleanArray for int to boolean'

These are even more efficient than storing boxed primitives inside a generic map.

java
SparseIntArray counts = new SparseIntArray();
counts.put(7, 3);
System.out.println(counts.get(7));

If your values are also primitive, use the specialized class instead of boxing both sides unnecessarily.

Do not over-optimize blindly

Even though SparseArray is often the better Android choice for integer keys, that does not mean every HashMap<Integer, T> must be replaced. If the map is tiny, rarely used, or lives outside performance-sensitive code, the simpler or more interoperable type may be fine.

The right approach is to choose SparseArray when the key type and usage pattern naturally match it, especially in allocation-sensitive paths.

Common Pitfalls

  • Comparing SparseArray to HashMap without noting that the usual comparison is really against HashMap<Integer, T>.
  • Assuming HashMap is always faster in practice because of the textbook average-case lookup complexity.
  • Using SparseArray with the expectation that it behaves exactly like the full Java Map API.
  • Ignoring specialized classes such as SparseIntArray when both keys and values are primitive.
  • Rewriting non-critical code purely for micro-optimization without measuring or considering readability.

Summary

  • 'SparseArray is mainly an Android optimization for int keys.'
  • It usually saves memory by avoiding Integer boxing and extra map structure overhead.
  • 'HashMap is more flexible and remains the normal choice for non-integer keys.'
  • For primitive-heavy Android code, sparse collections are often the better fit.
  • Choose based on key type, memory sensitivity, and real usage patterns rather than slogans.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.