具有多个键的字典Java映射
我需要创建一个地图,有3列:2个键和1个值。因此,每个值将包含两个不同类类型的键,并且可以使用其中一个来获取。但我的问题是HashMap/Map只支持1个键和1个值。有没有办法创建类似于Map<Key1, Key2, Value>
而不是Map<Key, Value>
的东西?因此Value
可以通过使用其Key1
或Key2
来获取
我很抱歉,如果这是一个重复或错误的问题,但我在堆栈溢出上找不到类似的问题
附言:我不想创建两个映射:Map<Key1, Value>
和Map<Key2, Value>
也不想创建嵌套映射我正在寻找一个多键表,就像上面那样
# 1 楼答案
要实现这一点,您可能需要编写一个类映射的自定义实现。我同意上面的@William Price,最简单的实现就是封装两个Map实例。使用Map接口时要小心,因为它们依赖equals()和hashCode()作为密钥标识,而您打算在合同中破坏密钥标识
# 2 楼答案
看看番石榴的桌子系列,可以在你的环境中使用
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html
# 3 楼答案
你看过Apache Commons Collection多地图界面了吗? https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/MultiMap.html
# 4 楼答案
根据自己的要求编写课程:
# 5 楼答案
只需将值存储两次:
问题是,键是什么类型并不重要,所以使用一个允许两种键类型的泛型绑定-
Object
就可以了请注意,^{} 方法的参数类型只是} 相关)
Object
,所以从查找的角度来看,拥有单独的映射没有任何价值(键的类型只与^{