Funwise Funwise - 1 year ago 85
Android Question

What is SparseBooleanArray in Android?

  • What is SparseBooleanArray?

  • When is it used? (kinly mention the cases)

  • How to use it?

Explain it with an example in simple terms and illustrated if possible?

Answer Source

SparseBooleanArray is functionally equivalent to a Map between Integer Objects and Boolean objects.

As the documentation states:

Unlike a normal array of booleans there can be gaps in the indices.

This might allow you to use it to map any integer values to booleans e.g. Years in which some event happened.

The reason to use this over a Map of Integers to Booleans is for performance. The system will automatically convert Integer objects to their primitive equivalents (Integer -> int, Boolean -> boolean) in a process called Autoboxing. See this video for more information:

As for how to use it, simply create a new instance of the object:

SparseBooleanArray array = new SparseBooleanArray()

And populate it using:

array.put(position, value)

where position is an int and value is a boolean.