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

来源:互联网 发布:深证指数数据 编辑:程序博客网 时间:2024/05/29 09:04

使用类集可以表示出以下关系:一个学校可以包含多个学生,一个学生属于一个学校。这是一个典型的一对多的关系。

学生含有的属性:姓名,年龄,对应的学校;

学校的属性:学校名称,对应的学生集合。

分析存储结构图:


先定义一个学生类:

public class Student {private String name;private int age;private School school;//一个学生有一个学校属性public Student(){}public Student(String name,int age){this.name = name;this.age = age;}public 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 School getSchool() {return school;}public void setSchool(School school) {this.school = school;}//重写equals方法(list存储的话不需要重写)public boolean equals(Object obj){if(this == obj){return true;}if(!(obj instanceof Student)){return false;}Student stu = (Student) obj;if(this.name.equals(stu.name) && this.age==stu.age){return true;}else{return false;}}//重写HashCode(list存储的话不需要重写)public int hashCode(){return this.name.hashCode()*this.age;}//重写toStringpublic String toString(){return "姓名:"+this.name+",年龄:"+this.age;}}

定义学校类:

public class School {private String name;private List<Student> allStudent;//一个学校对应多个学生public School(){this.allStudent = new ArrayList<Student>();//无参构造实例化list集合}public School(String name){this();//调用无参构造this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public List<Student> getAllStudent() {return allStudent;}public void setAllStudent(List<Student> allStudent) {this.allStudent = allStudent;}//重写toStringpublic String toString(){return "学校名称:"+this.name;}}

测试程序:

public class Demo01 {public static void main(String[] args) {//实例化学校对象School sch1 = new School("清华大学");School sch2 = new School("北京邮电大学");//实例化学生对象Student stu1 = new Student("张三",20);Student stu2 = new Student("李四",21);Student stu3 = new Student("王五",22);Student stu4 = new Student("赵六",23);//在学校中加入学生sch1.getAllStudent().add(stu1);sch1.getAllStudent().add(stu2);sch2.getAllStudent().add(stu3);sch2.getAllStudent().add(stu4);//一个学生属于一个学校stu1.setSchool(sch1);stu2.setSchool(sch1);stu3.setSchool(sch2);stu4.setSchool(sch2);System.out.println(sch1);Iterator<Student> iter = sch1.getAllStudent().iterator();while(iter.hasNext()){System.out.println(iter.next());}System.out.println(sch2);for(Student students : sch2.getAllStudent()){System.out.println(students);}}}

输出结果:

学校名称:清华大学姓名:张三,年龄:20姓名:李四,年龄:21学校名称:北京邮电大学姓名:王五,年龄:22姓名:赵六,年龄:23
1、分析存储及其关系结构;2、定义类和各个属性,通过两个类中的属性保存彼此引用关系


1 0