Map with two-dimensional key in java

2019-03-17 22:40发布

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)

标签: java hash map
7条回答
你好瞎i
2楼-- · 2019-03-17 23:19

You should use Map<Pair<K1,K2>, V>

  1. It will only contain one map, instead of N+1 maps

  2. Key construction will be obvious (creation of the Pair)

  3. Nobody will get confused as to the meaning of the Map as its programmer facing API won't have changed.

  4. Dwell time in the data structure would be shorter, which is good if you find you need to synchronize it later.

查看更多
登录 后发表回答