Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through SparseArray?

Tags:

java

android

Is there a way to iterate over Java SparseArray (for Android) ? I used sparsearray to easily get values by index. I could not find one.

like image 239
Ruzanna Avatar asked Nov 03 '11 17:11

Ruzanna


People also ask

Is it possible to iterate through a set?

There is no way to iterate over a set without an iterator, apart from accessing the underlying structure that holds the data through reflection, and replicating the code provided by Set#iterator...

What is the best way to iterate a list?

The best way to iterate the list in terms of performance would be to use iterators ( your second approach using foreach ).

Can you iterate over integers?

Since integers, individualistically, are not iterable, when we try to do a for x in 7 , it raises an exception stating TypeError: 'int' object is not iterable .

Can you iterate through an object Java?

forEach() method is available in Java 8 and each collection has this method that implements the iteration internally. Syntax used : With iterable variable.


2 Answers

Seems I found the solution. I hadn't properly noticed the keyAt(index) function.

So I'll go with something like this:

for(int i = 0; i < sparseArray.size(); i++) {    int key = sparseArray.keyAt(i);    // get the object by the key.    Object obj = sparseArray.get(key); } 
like image 101
Ruzanna Avatar answered Sep 17 '22 22:09

Ruzanna


If you don't care about the keys, then valueAt(int) can be used to while iterating through the sparse array to access the values directly.

for(int i = 0, nsize = sparseArray.size(); i < nsize; i++) {     Object obj = sparseArray.valueAt(i); } 
like image 36
Pogo Lin Avatar answered Sep 19 '22 22:09

Pogo Lin