哈希映射 – 使用布尔值

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

Hashmaps - using booleans

问题

使用两个不同的哈希映射和一个布尔函数实现了一个包含哈希映射的Java程序。因此,对于每个键,根据布尔结果,它会选择其中一个哈希映射。这种方法的一些优缺点是什么?

英文:

I was implementing a Java program containing hash maps, I wanted to use two different hash-maps and a boolean function. So for every key, depending on the boolean outcome, it would select one of the hash-maps. What would be some disadvantages/advantage of this?

答案1

得分: 0

有两种方法可以做到这一点(就我目前所思):

方法1:(来自评论中的@WJS)

使用一个具有布尔键和相应的HashMap作为值的HashMap。像这样:

HashMap<Boolean, Map<Key, Value>> outer = new HashMap<>();

方法2:
由于只有两个HashMap与您的布尔值 truefalse 相对应,我认为您不需要另一个HashMap,可以简单地使用一个布尔变量。

例如:

// 或根据您的实现和需求类似;可以扩展以选择get()、set()等。

boolean flag;
HashMap<Key, Value> trueMap = new HashMap<>();
HashMap<Key, Value> falseMap = new HashMap<>();

HashMap<Key, Value> map = flag ? trueMap : falseMap;

像这样选择HashMap没有任何缺点,实际上相当常见。

英文:

There are two ways to do this (as far as I can think of at the moment):

Method 1: (from @WJS in the comments)

Have a HashMap with a boolean key and the corresponding HashMap as the value. Like so:

HashMap&lt;Boolean, Map&lt;Key, Value&gt;&gt; outer = new HashMap&lt;&gt;();

Method 2:
Since there can only be two HashMaps corresponding to your boolean true or false value, I don't think you need to have another HashMap and can simply use a boolean variable.

For Example:

// or similar depending on your implementation and needs; can be 
// extended for choosing get(), set(), etc.

boolean flag;
HashMap&lt;Key, Value&gt; trueMap = new HashMap&lt;&gt;();
HashMap&lt;Key, Value&gt; falseMap = new HashMap&lt;&gt;();

HashMap&lt;Key, Value&gt; map = flag ? trueMap : falseMap;

There is no downside to having HashMaps chosen like this and is actually fairly common.

huangapple
  • 本文由 发表于 2020年8月20日 01:36:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63492218.html
匿名

发表评论

匿名网友

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

确定