英文:
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与您的布尔值 true 或 false 相对应,我认为您不需要另一个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<Boolean, Map<Key, Value>> outer = new HashMap<>();
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<Key, Value> trueMap = new HashMap<>();
HashMap<Key, Value> falseMap = new HashMap<>();
HashMap<Key, Value> map = flag ? trueMap : falseMap;
There is no downside to having HashMaps chosen like this and is actually fairly common.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论