Implementing a Map with Multiple Keys
Question:
How can I create a data structure that behaves like a Map but uses multiple (differently-typed) keys to access its values? The keys are guaranteed to be unique. I need methods like getByKey1, getByKey2, containsKey1, and containsKey2.
Answer:
One approach is to use two internal Maps:
This method allows you to search values using either key because each key has its own Map.
Additional Notes:
Example Code:
<code class="java">import java.util.HashMap; import java.util.Map; class MyMap<K1, K2, V> { private Map<K1, V> map1; private Map<K2, V> map2; public MyMap() { map1 = new HashMap<>(); map2 = new HashMap<>(); } public V getByKey1(K1 key) { return map1.get(key); } public V getByKey2(K2 key) { return map2.get(key); } public boolean containsKey1(K1 key) { return map1.containsKey(key); } public boolean containsKey2(K2 key) { return map2.containsKey(key); } public void put(K1 key1, K2 key2, V value) { map1.put(key1, value); map2.put(key2, value); } }</code>
The above is the detailed content of How to Create a Map with Multiple Keys for Value Access?. For more information, please follow other related articles on the PHP Chinese website!