By Tony Bevis on Sunday, 15 October 2023
Category: Java

Java programming course: 11.4 Using a Map for zookeeper's responsibilities

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:


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:


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:


Here is the method:


In the main() method of Experiments you can now invoke the above method:

In the next series of lesson we will look at multithreading.

Next lesson: 12.1 Multithreading

Related Posts

Leave Comments