Java类集学习(七)应用范例(多对多的关系)

来源:互联网 发布:cosplay软件 编辑:程序博客网 时间:2024/06/06 08:31

上文讲到一对多的关系,定义类和各个属性,通过两个类中的属性保存彼此引用关系。

下面实现一个多对多的实例:一个学生可以选多门课程,一门课程可以有多个学生参加。

由此可见这是一个典型的多对多的关系,要定义学生类和课程类,学生的属性中开辟一个保存课程的list,课程类中开辟一个保存学生的list,通过无参构造把list实例化出来,有参构造把无参构造通过this();引进来带上,然后设置其他有参构造。

具体代码:

public class Student {private String name;private int age;private List<Course> allcourse;//声明一个占内存allCoursepublic String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public List<Course> getAllcourse() {return allcourse;}public void setAllcourse(List<Course> allcourse) {this.allcourse = allcourse;}public Student(){this.allcourse  = new ArrayList<Course>();//实例化allCourse开辟堆内存,准备着存放课程集合}public Student(String name, int age){this();//调用无参构造,把开辟的allCourse带过来,设置name,age 属性this.name = name;this.age = age;}public String toString(){return "姓名:"+this.name+",年龄:"+this.age;}}

public class Course {private String name;private int credit;//学分private List<Student> allStudent;//声明allStudent开辟栈内存public String getName() {return name;}public void setName(String name) {this.name = name;}public float getCredit() {return credit;}public void setCredit(int credit) {this.credit = credit;}public List<Student> getAllStudent() {return allStudent;}public void setAllStudent(List<Student> allStudent) {this.allStudent = allStudent;}public Course(){this.allStudent = new ArrayList<Student>();//实例化allStudent,开辟堆内存准备放学生集合}public Course(String name, int credit){this();//调用无参构造,把开辟的allStudent带过来,设置name,score属性this.name = name;this.credit = credit;}public String toString(){return "课程名称:"+this.name+",学分"+this.credit;}}
测试:

public class TestDemo {public static void main(String[] args) {Student s1 = new Student("张三",20);Student s2 = new Student("李四",22);Student s3 = new Student("王五",23);Course c1 = new Course("计算机",4);Course c2 = new Course("英语",3);Course c3 = new Course("数学",4);//学生选课,学生中增加课程信息s1.getAllcourse().add(c1);s1.getAllcourse().add(c2);s2.getAllcourse().add(c3);s2.getAllcourse().add(c2);s2.getAllcourse().add(c1);s3.getAllcourse().add(c2);//课程中增加学生信息c1.getAllStudent().add(s2);c1.getAllStudent().add(s1);c2.getAllStudent().add(s3);c2.getAllStudent().add(s1);c3.getAllStudent().add(s2);//输出一门课程的信息System.out.println(c1);//利用foreach输出每个课程学生的信息for(Student students : c1.getAllStudent()){System.out.println(students);}//输出一个学生的信息System.out.println("\n"+s2);//利用Iterator迭代输出一个学生所有课程信息Iterator<Course> iter = s2.getAllcourse().iterator();while(iter.hasNext()){System.out.println(iter.next());}}}
输出结果:

课程名称:计算机,学分4姓名:李四,年龄:22姓名:张三,年龄:20姓名:李四,年龄:22课程名称:数学,学分4课程名称:英语,学分3课程名称:计算机,学分4
Java类集的学习比较全部完成,主要常用的还是List接口(ArrayList)、Map(HashMap),以及集合的输出:Iterator、foreach,还有自定义的类中判断重复的方法:重写equals(),HashCode();若集合HashSet中要添加的元素是自定义的类,HashMap中K是自定义的类那么在自定义的类中就要重写这两个方法,用来去重。

1 0
原创粉丝点击