Before writing any code, you should make sure that you've carefully planned the classes you'll create. Based on the written functional requirements in items 1, 2, and 3 from the previous list, you can establish a class diagram that looks something like Figure 5-1.
To handle the operations to add, remove, and get members "in a predictable, obvious way,'' users of this object need to be allowed to specify a useful key name when adding the objects. The key will work just like a string index in an associative array, specifying the location in the collection into which the member object of the collection will be stored. This key can then be used for retrieving or removing the object later. To use our previous example of the registrar's office application, the key for each course might be the course code (for example, CS101 for a beginning computer science class). In some cases, you won't have a meaningful key value to use. In this situation, the collection should be able to determine a valid key on its own. The updated UML diagram is shown in Figure 5-2.
The obj parameter to addItem() is the item being added to the collection. This item is usually an object but can be any valid data type. The key parameter to addItem(), removeItem(), and getItem() is a string (optional in addItem()) representing the key.
After the basic code for manipulating the collection's contents has been established, we'll return to this diagram to explain how the lazy instantiation code will work. One final thing to note here is that length() simply returns the number of items currently in the collection.