31

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.

4

3 回答 3

42

这将只获得值,忽略索引之间的差距(就像您现有的 Map 解决方案所做的那样):

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;
}
于 2013-06-09T09:16:56.167 回答
2

ArrayMap看起来是一个更好的选择,它从 API 19 开始可用。

于 2016-12-11T16:23:43.343 回答
0

科特林版本:

   fun <T> SparseArray<T>.values(): List<T> {
        val list = ArrayList<T>()
        forEach { _, value ->
            list.add(value)
        }
    return  list.toList()
于 2019-11-04T13:56:54.097 回答