如何实现具有多个键的 Map? [英] How to implement a Map with multiple keys?
问题描述
我需要一个像 Map 一样的数据结构,但使用多个(不同类型的)键来访问其值.
(不要太笼统,我们说两个键)
I need a data structure which behaves like a Map,
but uses multiple (differently-typed) keys to access its values.
(Let's not be too general, let's say two keys)
键保证是唯一的.
类似于:
MyMap<K1,K2,V> ...
使用如下方法:
getByKey1(K1 key)...
getByKey2(K2 key)...
containsKey1(K1 key)...
containsKey2(K2 key)...
您有什么建议吗?
我唯一能想到的是:
编写一个内部使用两个 Map 的类.
The only thing I can think of is:
Write a class which uses two Maps internally.
编辑有些人建议我使用 tuple、pair 或类似的作为键Java 的地图,但这对我不起作用:
如上所述,我必须能够仅通过指定的两个键之一来搜索值.
地图使用键的哈希码并检查它们的相等性.
EDIT
Some people suggest me to use a tuple, a pair, or similar as a key for
Java's Map, but this would not work for me:
I have to be able, as written above, to search values by only one of the two keys specified.
Maps use hash codes of keys and check for their equality.
推荐答案
两张地图.一个Map
和一个Map
.如果您必须有一个接口,请编写一个实现上述方法的包装类.
Two maps. One Map<K1, V>
and one Map<K2, V>
. If you must have a single interface, write a wrapper class that implements said methods.
这篇关于如何实现具有多个键的 Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!