Java多对多映射
多对对的映射,可以用学生和课程进行演示。一个学生可以选择多个课程,一个课程又对应了多个学生
定义学生类
class Stu{ private String name; private String num; private Course[] course; public Stu() {} public Stu(String name,String num) { this.name = name; this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public Course[] getCourse() { return course; } public void setCourse(Course[] course) { this.course = course; } public String getInfo() { return "姓名 :"+name+" 学号 :"+num; } }
定义课程 类
class Course{ private String name; private Stu[] stu; public Course() {} public Course(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Stu[] getStu() { return stu; } public void setStu(Stu[] stu) { this.stu = stu; } public String getInfo() { return "课程 :"+name; } }
在main方法测试
首先定义Stu和Course对象,分别有三个
Stu s1 = new Stu("张三","001"); Stu s2 = new Stu("李四","002"); Stu s3 = new Stu("王五","003"); Course c1 = new Course("Java"); Course c2 = new Course("php"); Course c3 = new Course("Python");
设置彼此的关系,每个对象都有多个对象对应
//设置学生和课程的关系 s1.setCourse(new Course[]{c1,c2}); s2.setCourse(new Course[]{c1,c3}); s3.setCourse(new Course[]{c2,c3}); //相应的课程设置与学生的关系 c1.setStu(new Stu[]{s1,s2}); c2.setStu(new Stu[]{s1,s3}); c3.setStu(new Stu[]{s2,s3});
根据学生,获取课程信息
System.out.println(s1.getInfo()+" 同学选择的课程有"); for(int i=0; i<s1.getCourse().length; i++) { System.out.println(s1.getCourse()[i].getInfo()); }
运行
根据课程,获取学生信息
System.out.println(c2.getInfo()+" 选择这门课程的学生信息"); for(int i=0; i<c2.getStu().length; i++) { System.out.println(c2.getStu()[i].getInfo()); }
运行