Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a SparseArray to ArrayList?

Tags:

java

android

I know this is possible:

Map<Integer, Object> map = new HashMap<Integer, Object>();
...
List<Object> arrayList = new ArrayList<Object>(map.values());

But according to android SparseArray<Object> is more efficient, hence, I am wondering if it is possible to convert a SparseArray to Arraylist.

Much appreciate any input.

like image 562
LuckyMe Avatar asked Jun 09 '13 09:06

LuckyMe


2 Answers

This will get just the values, ignoring gaps between indices (as your existing Map solution does):

public static <C> List<C> asList(SparseArray<C> sparseArray) {
    if (sparseArray == null) return null;
    List<C> arrayList = new ArrayList<C>(sparseArray.size());
    for (int i = 0; i < sparseArray.size(); i++)
        arrayList.add(sparseArray.valueAt(i));
    return arrayList;
}
like image 140
Nick Avatar answered Nov 18 '22 12:11

Nick


ArrayMap looks like a better choice, which is available since API 19.

like image 25
Sah Avatar answered Nov 18 '22 13:11

Sah