2 HashMaps VS HashMap contain Pair

huangapple go评论78阅读模式
英文:

2 HashMaps VS HashMap contain Pair

问题

在开发服务过程中,我遇到了一个问题,我需要在以下两种解决方案中选择一种:

  • 使用两个哈希映射(hashmaps)
  • 使用一个包含值对的哈希映射(hash map)。

目前我有一个使用两个哈希映射的选项,然而我经常需要使用相同的键从两个哈希表中获取值。

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);}
}

我在考虑将代码改为以下方式:

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

在大型哈希表上,这样做会更有效吗?

英文:

During the development of the service, I have a problem where I need to choose one of two solutions

  • use 2 hashmaps
  • use one hash map containing a pair of values.

Currently I have an option with 2 hashmaps, however I often need to get values ​​from two hash tables using the same key.

class C {
Map&lt;String, A&gt; a = new HashMap&lt;&gt;();
Map&lt;String, B&gt; b = new HashMap&lt;&gt;();

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&lt;String, Pair&lt;A, B&gt;&gt; a_b = new HashMap&lt;&gt;();
Pair&lt;A, B&gt; getAB(String str){return a_b.get(str);}
}

Will it be more efficient on a large hash table?

答案1

得分: 3

我认为这个问题与效率或性能关系不大,更关乎于何种方式更有意义。为了回答何种方式更有意义,就必须考虑上下文。如果这两个哈希映射的值彼此依赖,并且构成一个逻辑单元,可以封装成一个类(或者如果更合适的话,使用一个对偶)。如果这些值不直接相关,只在一种情境下作为配对有意义,在另一种情境下作为独立的事物有意义,那么考虑使用两个映射。

英文:

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). 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.

huangapple
  • 本文由 发表于 2020年5月29日 04:50:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/62074298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定