As the title says, is there a way for me to have a sparse int array in Java? Something like int[]
or Integer[]
, but each element in the array should not take up space until it is actually written to with a non-zero value. This is because I want to optimise memory as much as possible (as most of the elements in the array would be 0/empty), yet have the option to look up by index, as with a standard array. I've considered the below options before asking this question:
- I am aware of options such as https://developer.android.com/reference/android/util/SparseIntArray. The problem is that they seem to be Android-specific, and I could not find a desktop equivalent.
- My understanding is that
int[]
andInteger[]
are not sparse arrays; even if I were to keep the elements of anInteger
array asnull
, it would still take up space, which wouldn't work for me. - The other option is to use hashmaps. While that works, it does take up non-insignificant amount of space (which is an issue in this particular case).
- Options like linked lists or an arraylist (of
Pairs
for instance) won't work since lookups are difficult that way.