Example: Generic Collections

The following UML diagram depicts a typical aggregation: A course contains a collection of students called "roster".

It also depicts a qualified association: A course contains a collection of lists called "grades". Furthermore, this collection is indexed by students.

jcf3

Assume the Student class is already declared:

class Student { ... }

We interpret the student roster to be a Java set because we want to avoid repeated elements and because there is no natural order or indexing implied by the diagram.

In order to index grades by students we must use a Java map:

public class Course {
   private Set<Student> roster = new HashSet<Student>();
   private Map<Student, List<Integer>> grades =
      new Hashtable<Student, List<Integer>>();

   public void add(Student s) {
      roster.add(s);
      grades.put(s, new LinkedList<Integer>());
   }
   public void remove(Student s) {
      roster.remove(s);
      grades.remove(s);
   }
   public Iterator<Student> iterator() { return roster.iterator(); }

   public void addScore(Student s, Integer score) {
      List<Integer> scores = grades.get(s);
      scores.add(score);
   }
   public double average(Student s) {
      List<Integer> scores = grades.get(s);
      double result = 0;
      for(Integer score: scores) {
         result += score;
      }
      return result/scores.size();
   }
   // usage:
   public static void main(String[] args) {
      Student s1 = new Student();
      Student s2 = new Student();
      Student s3 = new Student();
      Course cs1 = new Course();
      cs1.add(s1);
      cs1.add(s2);
      cs1.add(s3);
      cs1.addScore(s1, 100);
      cs1.addScore(s1, 90);
      cs1.addScore(s1, 80);
      System.out.println("avg = " + cs1.average(s1)); // prints 90
   }
}