Why does SparseIntArray not implement Map <Integer, Integer>?
Android API SparseIntArray API documentation opens with
SparseIntArrays converts integers to integers.
I am curious why it does not implement Map <Integer, Integer> .
It seems to me that all that would be required is a few different method names, a few simple additional methods and a bit of code to prohibit keys and null values โโ... of course, nothing that EnumMap can handle grace. Am I missing something?
This is not intended to be scrollable by Android API designers. Usually, when I wonder about things like this , there is a good reason, and I will learn something about the language or the platform.
JavaDoc for SparseIntArray also says
SparseIntArrays converts integers to integers. Unlike a regular array of integers, there can be spaces in the indices. It is assumed that this is more efficient memory than using a HashMap to match integers with integers , since it avoids automatic box keys and values โโand their data, the structure does not rely on an additional input object for each display.
We can get the following reasons for choosing SparseIntArray over Map <Integer, Integer>:
- Since we wanted to have a comparison between primitive ints, it would be useful to avoid autoboxing.
- In Map, having an object as a key / value, the complexity of computing a hash arises, resolving a hash collision, linking several records in one bucket, etc. This is not necessary since we are dealing with a primitive key / value pair. Please note that SparseIntArray comes with a performance warning. Since the values โโare stored in the data structure of the binary search tree array, inserting and deleting will be costly operations. Therefore, it is a good choice for a small data set.
As a side point, I would say that JavaDoc should be more specific by saying
"SparseIntArrays maps primitive integers to integers."
instead of talking
"SparseIntArrays converts integers to integers.
Mapimplementation is very difficult. You need methods likeentrySetandkeySet, which is not convenient inSparseIntArray.The keys of the card are objects, so you need constant boxing / unpacking.
SparseIntArrayoffers another way to list through aMap, using its specifickeyAtandvalueAt, which are very fast.
If SparseIntArray implemented by Map<Integer, Integer> , you will be tempted to write:
Map<Integer, Integer> intMap = new SparseIntArray(); But then you would only be stuck with Map enumeration capabilities.