I have a Tuple object that holds 3 primitives: Tuple(double, long, long). To avoid creating a huge amount of Tuple, I’m thinking using Trove library’s primitive MAP, which would take two primitive as key and value. In my case, it would be Map<double, some primitive>.
My question: is it possible efficiently to encode the two long into a single primitive that I can store in the map, and later decode them?
It’s right, you cannot pack two 64-bit primitives into another primitive, which is at most 64 bits of size. Both,
doubleandlongby standard are mapped by 64 binary digits.The question is, whether you can impose some restrictions on the numbers you are dealing with. If you know, you will always have even numbers or uneven numbers or the first component will have integer range or you are dealing with multitudes of 1000, you can win some bits here.
Practically speaking, you will never make use of all
of pairs of long values.
On the other hand, it’s no big deal to handle maps on pairs of values. That was the whole effort to make object-oriented languages like Java to not only deal with data types like
structin C, but also to bind methods to the data.You can find good implementations of a Pair class in the web, e.g. angelikalanger.com. Or you can easily code an implementation yourself, especially, since you only need a pair of
Longvalues.Also consider to use
Pair<Double, Pair<Long, Long>>or implement aTuple<M,N,T>class right away instead of a Map, i.e. key-value combination, following the outline of thePair<M,N>implementation.Finally, you could even employ an in-memory database like H2 to hold your
Tuple(double, long, long)entries. It is enough to enclose it in your project as a Java library and configure it properly.By the way, a 3-tuple is called a triple. Therefore, you could correctly call your
class Triple(double, long, long)or betterTriple(Double, Long, Long).