In the previous lesson we looked an maps.
Using a Map for zookeeper's responsibilities
At the zoo, each zookeeper is responsible for certain pens, as listed below:
- Alice looks after the monkeys and penguins
- Bob looks after the lions, monkeys and penguins
- Charles only looks after the penguins
This can be modelled using a Map by taking the view that each zookeeper will be the "key" and each will require an associated value of a collection of pens.
In the ZooAdministrator class declare a new instance variable called responsibilities that will be a Map, keyed by ZooKeeper objects and with the associated value being a collection of Pen objects:
Define a new private method createExampleResponsibilities() which will instantiate the map as a HashMap and then assign the appropriate pens into the map, for each zookeeper:
- Note how for each zookeeper, a
HashSetis used to group the relevant pens, and this is used as the value argument when being placed into the map, which is keyed on theZooKeeperobject.
You can now invoke the method at the end of the constructor:
It will be useful to output each zookeeper's responsibilities, so define a new method in ZooAdministrator called showZooKeeperResponsibilities(). This will contain some nested loops:
- The outer loop will iterate over each zookeeper in turn
- For each zookeeper, a second loop will iterate over each pen the zookeeper is responsible for in turn
- For each pen, a third loop will iterate over each of the animals that exist in that pen in turn, sending the animal's state to output.
Here is the method:
- You will see each nested loop indented inside the one outside of it.
In the main() method of Experiments you can now invoke the above method:
In the next series of lesson we will look at multithreading.