I want a map indexed by two keys (a map in which you put AND retrieve values using two keys) in Java. Just to be clear, I'm looking for the following behavior:
map.put(key1, key2, value); map.get(key1, key2); // returns value map.get(key2, key1); // returns null map.get(key1, key1); // returns null
What's the best way to to it? More specifically, should I use:
Map<K1,Map<K2,V>>
Map<Pair<K1,K2>, V>
Other?
(where K1,K2,V are the types of first key, second key and value respectively)
Unfortunately, the Java Map interface doesn't allow for multiple key types, so we need to find another solution.
Class MultiKeyMap<K,V> A Map implementation that uses multiple keys to map the value. This class is the most efficient way to uses multiple keys to map to a value.
A 2D array is just a bidimensional grid of objects, an HashMap is a special kind of associative array (called also dictionary or map) which associates generic keys to generic values.
Duplicate keys are not allowed in a Map. Basically, Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains an order of the objects but HashMap will not. HashMap allows null values and null keys.
You should use Map<Pair<K1,K2>, V>
It will only contain one map, instead of N+1 maps
Key construction will be obvious (creation of the Pair)
Nobody will get confused as to the meaning of the Map as its programmer facing API won't have changed.
Dwell time in the data structure would be shorter, which is good if you find you need to synchronize it later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With