University of Toronto - Fall 2000
Department of Computer Science

Week 9 - Vector of Vectors

We have a Vector of Students, with each Student containing a Vector of marks. Of course, the nested Vector of marks is "shielded" from the containing Vector by being a member of a protective Student class, but that's not necessary. You can just put a Vector into an element of another Vector if it seems appropriate ...

import java.util.*;
public class School2 {
        public static void main (String[] args) {

                Vector s0 = new Vector(); // the first student's marks
                Vector s1 = new Vector(); // the second student's marks
                Vector s2 = new Vector(); // the third student's marks

                // Let's make a lecture section of students:
                Vector course = new Vector();
                course.addElement(s0);
                course.addElement(s1);
                course.addElement(s2);

                // Add three marks for each student
                s0.addElement(new Integer(65));
                s0.addElement(new Integer(89));
                s0.addElement(new Integer(47));
                s1.addElement(new Integer(45));
                s1.addElement(new Integer(50));
                s1.addElement(new Integer(55));
                s2.addElement(new Integer(70));
                s2.addElement(new Integer(75));
                s2.addElement(new Integer(80));

                // Let's retrieve the second student's third mark:
                Vector stu = (Vector)course.elementAt(1);
                Integer mk = (Integer)stu.elementAt(2);
                int mark = mk.intValue();
                System.out.println ("2nd student's 3rd mark: " + mark);

                // Let's print all marks for all students:
                for (int i=0; i<course.size(); i++) {
                        Vector s = (Vector)course.elementAt(i);
                        System.out.print ("Student " + i +": ");
                        for (int j=0; j<s.size(); j++) {
                                System.out.print (s.elementAt(j) + " ");
                        }
                        System.out.println();
                }
        }
}

Program Output

2nd student's 3rd mark: 55
Student 0: 65 89 47
Student 1: 45 50 55
Student 2: 70 75 80

Memory Model Diagram