开发者

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 t开发者_JAVA百科able 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


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);
}


Use SparseArray.size() to get total size.

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


Here's how to display a SparseArray content for debug 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜