import java.util.List ; import java.util.ArrayList ; public class School{ private String name ; private List<Student> allStudents ; public School(){ this.allStudents = new ArrayList<Student>() ; } public School(String name){ this() ; this.setName(name) ; } public void setName(String name){ this.name = name ; } public String getName(){ return this.name; } public List<Student> getAllStudents(){ return this.allStudents ; } public String toString(){ return "学校名称:" + this.name ; } };
public class Student{ private String name ; private int age ; private School school; // 一个学生属于一个学校 public Student(String name,int age){ this.setName(name) ; this.setAge(age) ; } public void setSchool(School school){ this.school = school ; } public School getSchool(){ return this.school ; } public void setName(String name){ this.name = name ; } public void setAge(int age){ this.age = age ; } public String getName(){ return this.name; } public int getAge(){ return this.age ; } public String toString(){ return "学生姓名:" + this.name + ";年龄:" + this.age ; } };
import java.util.Iterator ; public class TestDemo{ public static void main(String args[]){ School sch = new School("清华大学") ; // 定义学校 Student s1 = new Student("张三",21) ; Student s2 = new Student("李四",22) ; Student s3 = new Student("王五",23) ; sch.getAllStudents().add(s1) ; sch.getAllStudents().add(s2) ; sch.getAllStudents().add(s3) ; s1.setSchool(sch) ; s2.setSchool(sch) ; s3.setSchool(sch) ; System.out.println(sch) ; Iterator<Student> iter = sch.getAllStudents().iterator() ; while(iter.hasNext()){ System.out.println("\t|- " + iter.next()) ; } } };