Java SparseArray 与 ArrayList 之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25444226/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:24:44  来源:igfitidea点击:

Difference between SparseArray Vs ArrayList?

javaandroid

提问by Amit Prajapati

I want to know performance and efficiency of SparseArrayand ArrayListand which one is better to use. I can't understand when to use SparseArrayand when ArrayList?

我想知道的性能和效率,SparseArray以及ArrayList和哪一个是更好地使用。我不明白什么时候用SparseArray,什么时候用ArrayList

采纳答案by chiastic-security

The purpose of a SparseArrayis to save memory if you have a list that has lots of gaps in. If you only have 10 items, and the numbers that index them range from 0 to 1000, then an ArrayListwill have lots of nullentries in it, and that will be quite wasteful. A SparseArraywill use data structures internally to avoid that problem.

SparseArray如果你有一个有很多空白的列表,a 的目的是节省内存。如果你只有 10 个项目,并且索引它们的数字范围从 0 到 1000,那么 aArrayList将有很多null条目,并且那将是相当浪费的。ASparseArray将在内部使用数据结构来避免该问题。

The alternative in this situation is a HashMap, which is better than a SparseArrayif you have lots of items.

这种情况下的替代方案是 a HashMapSparseArray如果您有很多项目,它比 a 更好。

The implementation is not intended to be appropriate for data structures that may contain large numbers of items. It is generally slower than a traditional HashMap, since lookups require a binary search and adds and removes require inserting and deleting entries in the array. For containers holding up to hundreds of items, the performance difference is not significant, less than 50%.

该实现不适用于可能包含大量项目的数据结构。它通常比传统的 HashMap 慢,因为查找需要二进制搜索,添加和删除需要在数组中插入和删除条目。对于最多容纳数百个项目的容器,性能差异并不显着,小于 50%。

From the Android dev documentation.

来自Android 开发文档

回答by Massimiliano Peluso

SparseList implements a SparseArray. This class is identical to java.util.ArrayList, except that the former permits assignment to array indexes that are beyond the current length of the list, using the expected set()and add()methods.*

SparseList 实现了一个SparseArray. 此类与 相同java.util.ArrayList,除了前者允许使用预期的set()add()方法分配给超出列表当前长度的数组索引。*

I think here there is all you need to know to understand which one to use.

我认为这里有所有你需要知道的来了解使用哪一个。

SparseList is also more efficient

SparseList 也更高效

more info here

更多信息在这里