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.

+6
source share
3 answers

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.

+3
source
  • Map implementation is very difficult. You need methods like entrySet and keySet , which is not convenient in SparseIntArray .

  • The keys of the card are objects, so you need constant boxing / unpacking.

  • SparseIntArray offers another way to list through a Map , using its specific keyAt and valueAt , 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.

+1
source

If he implemented Map<Integer,Integer> , he would have to deal with Integer objects as input and output values โ€‹โ€‹instead of primitive int values, so the whole point of this class, which should avoid boxing, would be lost.

0
source

All Articles