Team LiB
Previous Section Next Section

Collections As Method Return Types

Collections provide a way to overcome the limitation that we noted in Chapter 4 about methods only being able to return a single result. If we define a method as having a return type that is a collection type, we can hand back an arbitrary sized collection of object references to the client code that invokes the method.

In the code snippet shown next for the Course class, we provide a GetRegisteredStudents method to enable client code to request a "handle" on the entire collection of Student objects that are registered for a particular course:

public class Course
{
  private EnrollmentCollection enrolledStudents;

  // Other details omitted ...

  // The following method returns a reference to an entire collection
  // containing however many students are registered for the course in question.
  EnrollmentCollection GetRegisteredStudents() {
    return enrolledStudents;
  }
}

An example of how client code would then use such a method is as follows:

// Instantiate a course and several students.
Course c = new Course();
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();

// Enroll the students in the course.
c.Enroll(s1);
c.Enroll(s2);
c.Enroll(s3);

// Now, ask the course to give us a handle on the collection of
// all of its registered students ...
EnrollmentCollection ec = c.GetRegisteredStudents();

// ... and iterate through the collection, printing out a grade report for
// each Student (pseudocode).
for (each Student in EnrollmentCollection) {
  s.PrintGradeReport();
}
Note?/td>

Of course, if we return a direct handle on a collection such as enrolledStudents to client code, we are giving client code the ability to modify that collection (e.g., removing a Student reference). Design considerations may warrant that we create a copy of the collection before returning it, so that the original collection is not modified:

    public class Course
    {
      private EnrollmentCollection enrolledStudents;

      // Other details omitted ...

      // The following method returns a COPY of the Student's enrolledStudents
      // collection, so that client code can't modify the OFFICIAL version.
      EnrollmentCollection GetRegisteredStudents() {
        EnrollmentCollection temp = new EnrollmentCollection();

        // Pseudocode.
        copy contents of enrolledStudents to temp

        return temp;
     }
   }

Another way to avoid the problem of allowing client code to modify a collection in the previous example would be to have the GetRegisteredStudents method return an enumeration of the elements contained in the collection. We'll discuss how to use enumerators in Chapter 13.


Team LiB
Previous Section Next Section