I have a 2D array of Integers. I want them to be put into a HashMap. But I want to access the elements from the HashMap based on Array Index. Something like:
For A[2][5], map.get(2,5) which returns a value associated with that key. But how do I create a hashMap with a pair of keys? Or in general, multiple keys: Map<((key1, key2,..,keyN), Value) in a way that I can access the element with using get(key1,key2,…keyN).
EDIT : 3 years after posting the question, I want to add a bit more to it
I came across another way for NxN matrix.
Array indices, i and j can be represented as a single key the following way:
int key = i * N + j;
//map.put(key, a[i][j]); // queue.add(key);
And the indices can be retrevied from the key in this way:
int i = key / N;
int j = key % N;
There are several options:
2 dimensions
Map of maps
Wrapper key object
Implementing
equals()andhashCode()is crucial here. Then you simply use:and:
Tablefrom GuavaTableuses map of maps underneath.N dimensions
Notice that special
Keyclass is the only approach that scales to n-dimensions. You might also consider:but that’s terrible from performance perspective, as well as readability and correctness (no easy way to enforce list size).
Maybe take a look at Scala where you have tuples and
caseclasses (replacing wholeKeyclass with one-liner).