FREE BOOK

Chapter 6: Collections of Objects

Posted by Apress Free Book | C# Language December 16, 2008
The properties and behaviors of some common collection types,How collections enable us to model very sophisticated real-world concepts or situations,How we can define our own collection types

Dictionaries

A dictionary provides a means for storing each object reference along with a unique look-up key that can later be used to retrieve the object (see Figure 6-10). The key is typically contrived based on one or more of the object's attribute values; for example, in our SRS, a Student object's ID number would make an excellent key, because it's inherently unique for each student. Items in a dictionary can then be quickly retrieved based on this key. Items can typically also be retrieved one by one from a dictionary type collection in ascending key order.


Figure 6-10. Dictionary collections accommodate direct access by key.

The SRS might use a dictionary, indexed on a unique combination of course number plus section number, to manage its course catalog. With so many courses to keep track of, being able to "pluck"the appropriate Course object from a collection directly (instead of having to step through an ordered list one-by-one to find it) adds greatly to the efficiency of the application.

The C# Hashtable class is an example of a specific implementation of a dictionary.

Referencing the Same Object Simultaneously from Multiple Collections

As we mentioned earlier, when we talk about inserting an object into a collection, what we really mean is that we're inserting a reference to the object, not the object itself. This implies that the same object can be referenced by multiple collections simultaneously. Think of a person as an object, and his or her telephone number as a handle for reaching that person. Now, as we proposed earlier in this chapter, think of an address book as a collection: it's easy to see that the same person's phone number (reference) can be recorded in many different address books (collections) simultaneously.

Now, for an example relevant to the SRS: given the students who are registered to attend a particular course, we may simultaneously maintain the
following:

  • An ordered list of these students for purposes of knowing who registered first for a follow-on course
     
  • A dictionary that allows us to retrieve a given Student object based on his or her name
     
  • Perhaps even a second SRS-wide dictionary that organizes all students at the university based on their student ID numbers

This is depicted conceptually in Figure 6-11.



Figure 6-11. A given object may be referenced by multiple collections simultaneously.

Total Pages : 8 45678

comments