java 如何将 SparseArray 转换为 ArrayList?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17008115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a SparseArray to ArrayList?
提问by LuckyMe
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
.
但是根据 androidSparseArray<Object>
效率更高,因此,我想知道是否可以将 a 转换SparseArray
为Arraylist
.
Much appreciate any input.
非常感谢任何输入。
回答by Nick
This will get just the values, ignoring gaps between indices (as your existing Map solution does):
这将只获得值,忽略索引之间的差距(就像您现有的 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;
}
回答by Sah
回答by Dimka Swan
Kotlin version:
科特林版本:
fun <T> SparseArray<T>.values(): List<T> {
val list = ArrayList<T>()
forEach { _, value ->
list.add(value)
}
return list.toList()