import java.util.ArrayList;
public class Student{
private String name;
private int age;
private List<Course> allCourses;
public Student(){
this.allCourses=new ArrayList<Course>();
}
public Student(String name,int age){
this();
this.setName(name);
this.setAge(age);
}
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 List<Course> getAllCourses(){
return this.allCourses;
}
public String toString(){
return "姓名:"+this.getName()+";年龄:"+this.getAge();
}
};
import java.util.List;
import java.util.ArrayList;
public class Course{
private String name;
private int credit;
private List<Student> allStudents;
public Course(){
this.allStudents=new ArrayList<Student>();
}
public Course(String name,int credit){
this();
this.setName(name);
this.setCredit(credit);
}
public void setName(String name){
this.name=name;
}
public void setCredit(int credit){
this.credit=credit;
}
public String getName(){
return this.name;
}
public int getCredit(){
return this.credit;
}
public List<Student> getAllStudents(){
return this.allStudents;
}
public String toString(){
return "课程名称:"+this.getName()+";课程学分:"+this.getCredit();
}
};
/*实例二:多对多关系
要求:一个学生可以选多门课程,一们课程由多个学生组成,这就是典型的多对多关系
步骤:首先定义两个类:学生信息类Student,课程信息类Course,在一个学生类中存在一个集合,保存全部课程
而在课程信息类中也要存在一个集合,保存全部学生
*/
import java.util.Iterator;
public class TestDemo{
public static void main(String args[]){
Student s1=new Student("张三",22);
Student s2=new Student("李四",20);
Student s3=new Student("王五",24);
Student s4=new Student("赵六",21);
Student s5=new Student("孙七",27);
Student s6=new Student("李强",28);
Course c1=new Course("英语",5);
Course c2=new Course("语文",3);
Course c3=new Course("数学",7);
Course c4=new Course("物理",8);
Course c5=new Course("生物",2);
//是s1参加了三门课程
s1.getAllCourses().add(c1);
s1.getAllCourses().add(c2);
s1.getAllCourses().add(c3);
//c1课程有六个学生参加
c1.getAllStudents().add(s1);
c1.getAllStudents().add(s2);
c1.getAllStudents().add(s3);
c1.getAllStudents().add(s4);
c1.getAllStudents().add(s5);
c1.getAllStudents().add(s6);
//通过s1学生找到参加的课程
Iterator<Course> iter=s1.getAllCourses().iterator();
while(iter.hasNext()){
System.out.println("\t|-"+iter.next());
}
//通过c1课程名称找到参加学生
Iterator<Student> iter2=c1.getAllStudents().iterator();
while(iter2.hasNext()){
System.out.println("\t|-"+iter2.next());
}
}
};