001package edu.pdx.cs410J.j2se15;
002
003import java.util.*;
004
005/**
006 * This class demonstrates how generic collections can be used with
007 * legacy code that does not use generics.
008 *
009 * @author David Whitlock
010 * @since Winter 2005
011 */
012public class GenericsAndLegacy1 {
013
014  /**
015   * A "legacy" class that does not use generic collections.
016   */
017  static class Course {
018    private List allStudents = new ArrayList();
019
020    void addStudents(Collection students) {
021      for (Iterator iter = students.iterator(); 
022           iter.hasNext(); ) {
023        this.allStudents.add((Student) iter.next());
024      }
025    }
026
027    List getStudents() {
028      return this.allStudents;
029    }  
030  }
031
032  /**
033   * A student
034   */
035  static class Student {
036
037  }
038
039  /**
040   * A grad student
041   */
042  static class GradStudent extends Student {
043
044  }
045
046  /**
047   * A main program that uses generic collections with legacy code.
048   */
049  public static void main(String[] args) {
050    Course course = new Course();
051
052    Collection<Student> students = 
053      new ArrayList<Student>();
054    students.add(new Student());
055    students.add(new GradStudent());
056    course.addStudents(students);
057
058    Student student1 = (Student) course.getStudents().get(0);
059  }
060
061  /**
062   * A little method that shows that aliasing arrays of parameterized
063   * types are not allowed.  This code does not compile.
064   */
065//   private static void aliasingParameterArrays() {
066//     List<String>[] lsa = new List<String>[10]; // bad
067//     Object o = lsa;
068//     Object[] oa = (Object[]) o;
069//     List<Integer> ints = new ArrayList<Integer>();
070//     ints.add(new Integer(42));
071//     oa[1] = ints;  // No compiler warning, runtime okay
072//     String s = lsa[1].get(0);  // ClassCastException
073//   }
074
075}