I have Objects which need to be mapped to Integers (or primitive ints).
So for example
Object[] objects = new Object[X];
objects[2]=o1;
objects[34]=o2;
objects[126]=o3;
...
So I have a range from 0 to X for the keys but only need a few (lets say 20) mapping pairs.
(The mapping is only done once and will not change)
Would it be (performance and memory-usage vise) a better idea to use a Map (and if which implementation would suite best) instead of the “large” array which is mostly unused.
The needed range might actually scale up later during development – so if it is only important for very large X that would still be interesting for me. (Currently X is 256 – so rather small)
To sum it up: I want to efficiently map Numbers to Objects in Java.
whether you use the fastest possibility (array) or a
HashMapdepends on your application. Do you have millions of calculations (array accesses) per second? Yes then take the array, and spend the 1k of memory.Oherwise take the Map.
But there is a third solution if x is big:
This solution is nearly as fast as the map (maybe faster), but uses less space:
Use a sorted array of int as index into an object array:
Idx must be sorted ascending.
now get object for key 34:
But this i would use this only for a high number of objects with minimal storage space requirementm where objects do not change on runtime.