简体   繁体   English

2 HashMaps VS HashMap 包含对

[英]2 HashMaps VS HashMap contain Pair

During the development of the service, I have a problem where I need to choose one of two solutions在服务开发过程中,我遇到了一个问题,我需要从两个解决方案中选择一个

  • use 2 hashmaps使用 2 个哈希图
  • use one hash map containing a pair of values.使用一个 hash map 包含一对值。

Currently I have an option with 2 hashmaps, however I often need to get values from two hash tables using the same key.目前我有一个带有 2 个哈希图的选项,但是我经常需要使用相同的键从两个 hash 表中获取值。

class C {
Map<String, A> a = new HashMap<>();
Map<String, B> b = new HashMap<>();

A getA(String str){return a(str);}
B getB(String str){return b(str);}
}

I am thinking of changing the code as follows我正在考虑如下更改代码

class C {
Map<String, Pair<A, B>> a_b = new HashMap<>();
Pair<A, B> getAB(String str){return a_b.get(str);}
}

Will it be more efficient on a large hash table?在 hash 大表上效率会更高吗?

I think this question is not so much about efficiency or performance as it is what would make sense.我认为这个问题与其说是关于效率或性能,不如说是有意义的。 And to answer what would make sense, one would have to take context into cosideration.要回答什么是有意义的,就必须考虑上下文。 If the values of the two hashmaps are dependant on eachother and make a logical unit which could be encapsulated into a class then use a class (or a pair if it makes more sense).如果两个散列映射的值相互依赖并构成一个可以封装到 class 中的逻辑单元,则使用 class(或一对,如果它更有意义)。 If the values are not directly related and only make sense at one context as pairs but in another as separate things then consider using two maps.如果值不直接相关,并且仅在一个上下文中成对有意义,而在另一个上下文中作为单独的事物有意义,则考虑使用两个映射。

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

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