Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between SparseArray Vs ArrayList?

Tags:

java

android

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

like image 431
Amit Prajapati Avatar asked Aug 22 '14 09:08

Amit Prajapati


People also ask

What is SparseArray in Java?

SparseArray maps integers to Objects and, unlike a normal array of Objects, its indices can contain gaps. SparseArray is intended to be more memory-efficient than a HashMap , because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping.

What is the main difference between array and ArrayList?

Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed. We cannot store primitives in ArrayList, it can only store objects. But array can contain both primitives and objects in Java.

What is the difference between string array and ArrayList?

String[] is an array of Strings while ArrayList is a generic class which takes different types of objects (here it takes Strings). Therefore you can only perform normal array operations with String[].

What is the difference between array and ArrayList Which is better?

As we all are aware of that arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection framework.


1 Answers

The purpose of a SparseArray is 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 ArrayList will have lots of null entries in it, and that will be quite wasteful. A SparseArray will use data structures internally to avoid that problem.

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

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%.

From the Android dev documentation.

like image 178
chiastic-security Avatar answered Sep 28 '22 03:09

chiastic-security