Android: is there an idiom for iterating through SparseArray

I use the list of unique identifiers int for the list of usernames as a quick lookup table and decided to use sparseArray, but I would like to be able to print so that from time to time I register the entire list for debugging purposes,

SparseArray is not iterable and not very similar to util.Map interface

+8
android idioms sparse-array
source share
3 answers

The mice were correct, the code would look something like this:

for(int i = 0; i < sparseArray.size(); i++){ int key = sparseArray.keyAt(i); Object value = sparseArray.valueAt(i); } 
+14
source share

Use SparseArray.size () to get the total size.

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

+4
source share

Here's how to display the contents of a SparseArray for debugging traces.

 public static String sparseArrayToString(SparseArray<?> sparseArray) { StringBuilder result = new StringBuilder(); if (sparseArray == null) { return "null"; } result.append('{'); for (int i = 0; i < sparseArray.size(); i++) { result.append(sparseArray.keyAt(i)); result.append(" => "); if (sparseArray.valueAt(i) == null) { result.append("null"); } else { result.append(sparseArray.valueAt(i).toString()); } if(i < sparseArray.size() - 1) { result.append(", "); } } result.append('}'); return result.toString(); } 
0
source share

All Articles