Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Clear Purpose of SparseBooleanArray?? [ I referred official android site for this ]

Tags:

java

android

I referred the android doc site for "SparseBooleanArray" class but still not getting idea of that class about what is the purpose of that class?? For what purpose we need to use that class??

Here is the Doc Link http://developer.android.com/reference/android/util/SparseBooleanArray.html

like image 561
Ripal Tamboli Avatar asked Sep 16 '13 07:09

Ripal Tamboli


3 Answers

From what I get from the documentation it is for mapping Integer values to booleans.

That is, if you want to map, if for a certain userID a widget should be shown and some userIDs have already been deleted, you would have gaps in your mapping.

Meaning, with a normal array, you would create an array of size=maxID and add a boolean value to element at index=userID. Then when iterating over the array, you would have to iterate over maxID elements in the worst case and have to check for null if there is no boolean for that index (eg. the ID does not exist). That is really inefficient.

When using a hashmap to do that you could map the ID to the boolean, but with the added overhead of generating the hashvalue for the key (that is why it is called *hash*map), which would ultimately hurt performance firstly in CPU cycles as well as RAM usage.

So that SparseBooleanArray seems like a good middleway of dealing with such a situation.

NOTE: Even though my example is really contrieved, I hope it illustrates the situation.

like image 144
LuigiEdlCarno Avatar answered Oct 13 '22 09:10

LuigiEdlCarno


Like the javadoc says, SparseBooleanArrays map integers to booleans which basically means that it's like a map with Integer as a key and a boolean as value (Map).

However it's more efficient to use in this particular case It is intended to be more efficient than using a HashMap to map Integers to Booleans

Hope this clears out any issues you had with the description.

like image 45
Thihara Avatar answered Oct 13 '22 09:10

Thihara


I found a very specific and wonderful use for the sparse boolean array.

You can put a true or false value to be associated with a position in a list.

For example: List item #7 was clicked, so putting 7 as the key and true as the value.

like image 45
JamisonMan111 Avatar answered Oct 13 '22 07:10

JamisonMan111