范例讲解:多对多的关系

来源:互联网 发布:php 链接ftp源码 编辑:程序博客网 时间:2024/05/22 12:32

 实例要求:

1. 一个学生可选多门课程,一门课程可以有多个学生参加,那么这就是一个典型的多对多关系。

2.要完成本程序,首先应该定义两个类,学生信息类Student、课程信息类Course,在一个学生

类中存在一个集合,保存全部的课程,而在谭程类中要存在一个集合,保存全部的学生。

  课程类:

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.name = name ;this.credit = credit ;}public List<Student> getAllStudents(){return this.allStudents ;}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 String toString(){return "课程名称:" + this.name + ";课程学分:" + this.credit ;}};
 学生类:
import java.util.List ;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.name = name ;this.age = age ;}public List<Course> getAllCourses(){return this.allCourses ;}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 ;}};
 测试类:

<span style="font-size:10px;">import java.util.Iterator ;public class TestMore{public static void main(String args[]){Course c1 = new Course("英语",3) ;// 第一门课程Course c2 = new Course("计算机",5) ;// 第二门课程Student s1 = new Student("张三",20) ;Student s2 = new Student("李四",21) ;Student s3 = new Student("王五",22) ;Student s4 = new Student("赵六",23) ;Student s5 = new Student("孙七",24) ;Student s6 = new Student("钱八",24) ;// 第一门课程有三个学生参加c1.getAllStudents().add(s1) ;c1.getAllStudents().add(s2) ;c1.getAllStudents().add(s6) ;s1.getAllCourses().add(c1) ;s2.getAllCourses().add(c1) ;s6.getAllCourses().add(c1) ;// 第二门课程有六个学生参加c2.getAllStudents().add(s1) ;c2.getAllStudents().add(s2) ;c2.getAllStudents().add(s3) ;c2.getAllStudents().add(s4) ;c2.getAllStudents().add(s5) ;c2.getAllStudents().add(s6) ;s1.getAllCourses().add(c2) ;s2.getAllCourses().add(c2) ;s3.getAllCourses().add(c2) ;s4.getAllCourses().add(c2) ;s5.getAllCourses().add(c2) ;s6.getAllCourses().add(c2) ;// 输出一门课程的信息,观察一门课程有多少个学生参加\System.out.println(c1) ;Iterator<Student> iter1 = c1.getAllStudents().iterator() ;while(iter1.hasNext()){Student s = iter1.next() ;System.out.println("\t|- " + s) ;}// 通过学生找到学生参加的课程System.out.println(s6) ;Iterator<Course> iter2 = s6.getAllCourses().iterator() ;while(iter2.hasNext()){Course c = iter2.next() ;System.out.println("\t|- " + c) ;}}};</span>




0 0
原创粉丝点击