Hashmaps - using booleans

Viewed 112

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 Answers

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.

Related