Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Is there an idiom for Iterating through a SparseArray

I'm using a list of unique int ids against a list of user names as a fast lookup table and decided to use the sparseArray but I would like to be able print to log the entire list from time to time for debugging purposes.

The SparseArray is not iterable and isn't much like the util.Map interface

like image 978
user245357 Avatar asked Sep 05 '11 06:09

user245357


People also ask

What is sparse array in Android?

The sparse array is an array in which most of the elements have the same value(the default value is zero or null).

What is sparse array Kotlin?

android.util.SparseArray. SparseArray maps integers to Objects and, unlike a normal array of Objects, its indices can contain gaps. SparseArray is intended to be more memory-efficient than a HashMap , because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping.


2 Answers

Mice was correct, code would look something like this;

for(int i = 0; i < sparseArray.size(); i++){
    int key = sparseArray.keyAt(i);
    Object value = sparseArray.valueAt(i);
}
like image 124
Pork 'n' Bunny Avatar answered Sep 27 '22 18:09

Pork 'n' Bunny


Use SparseArray.size() to get total size.

Use SparseArray.keyAt and valueAt to get key/value in given index.

like image 41
Pointer Null Avatar answered Sep 27 '22 17:09

Pointer Null