简体   繁体   English

使用HashMap作为另一个HashMap的键

[英]Using a HashMap as a Key for another HashMap

I have a requirement where I need to map a set of configurations with a set of values, ideally denoted by a Map<Map<String, Object>, Map<String, Object>> structure. 我有一个要求,我需要使用一组值映射一组配置,理想情况下由Map<Map<String, Object>, Map<String, Object>>结构表示。

Both the configurations & the values part of the main Map are arbitrary & hence, I am unable to use a concrete class. 主Map的配置和值部分都是任意的,因此,我无法使用具体的类。

Please provide some feedback on this structure. 请提供一些有关此结构的反馈。 Can a Map be used as a key for another Map. 可以将地图用作另一个地图的关键字。 Doing a bit of research, I was able to establish that the Map's equals method utilizes all underlying Keys & Values to deem two Maps as equal. 做了一些研究,我能够确定Map的equals方法利用所有底层的Keys&Values来将两个Maps视为相等。 Also, the HashCode of a Map is based on the Hashcodes of the Map's Keys. 此外,Map的HashCode基于Map的Keys的Hashcodes。 This IMO should suffice the minimum requirements of using a Map as a key. 这个IMO应该满足使用Map作为关键字的最低要求。

I would still like someone to validate this before I go ahead with the implementation. 在我继续实施之前,我仍然希望有人来验证这一点。 In case there is a better solution / design that someone can suggest, please feel free to do so. 如果有更好的解决方案/设计,有人可以建议,请随时这样做。

EDIT 编辑

I ended up using a simple tilde ('~') & pipe ('|') separated String as the key & deconstructed it whenever needed. 我最终使用简单的代字号('〜')和管道('|')分隔String作为键并在需要时对其进行解构。 Thanks to all who helped. 感谢所有帮助过的人。

Yes, a HashMap can be used as a key to another map, as the class properly overrides .equals() and .hashCode() . 是的, HashMap 可以用作另一个映射的键,因为该类正确覆盖了.equals().hashCode()

However it's broadly speaking a bad idea to use mutable types (such as HashMap ) as Map keys or Set elements, because you violate the invariants these classes expect if the objects are mutated while in the collection. 然而,从广义上讲,使用可变类型 (例如HashMap )作为Map键或Set元素是一个坏主意 ,因为如果对象在集合中发生变异,则会违反这些类所期望的不变量。

While not quite what you're looking for, Guava offers several additional data structures such as Multiset , MultiMap , BiMap , Table which may be useful. 当你正在寻找不太什么, 番石榴提供了几个额外的数据结构 ,如MultisetMultiMapBiMapTable可能是有用的。 They also offer immutable collections such as ImmutableMap which (because they can't be mutated) are safer to use as a Map key. 它们还提供不可变集合,例如ImmutableMap (因为它们不能被变异)更安全地用作Map键。 Which isn't to say you should do so, simply that it's safe (if the keys and values are also immutable). 这并不是说你应该这样做,只是说它是安全的(如果键和值也是不可变的)。

Consider posting a question exploring the problem that lead you to conclude a Map<Map<K, V>, Map<K, V>> structure was what you needed. 考虑发布一个问题,探讨导致您得出Map<Map<K, V>, Map<K, V>>结构的问题。 You may get better answers to that question. 您可能会得到这个问题更好的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM