9、对象一对多与多对多关系
在学习完集合框 架后,我们可以使用集合来表示实际开发中对象的一对多关系和多对多关
系
一对多
public class OneToManyDemo {
public static void main(String[] args) {
Teacher t1=new Teacher("张老师",26,"女");
student s1=new student("李华",8);
student s2=new student("lili",6);
student s3=new student("小赵",7);
student s4=new student("小华",9);
//关联关系
t1.getStudents().add(s1);
t1.getStudents().add(s2);
t1.getStudents().add(s3);
t1.getStudents().add(s4);
s1.setTeacher(t1);
s2.setTeacher(t1);
s3.setTeacher(t1);
s4.setTeacher(t1);
print(t1);
}
private static void print(Teacher t1) {
System.out.println(t1.getName());
for(student s:t1.getStudents()) {
System.out.println(s);
}
}
}
张老师
student [name=小华, age=9]
student [name=李华, age=8]
student [name=lili, age=6]
student [name=小赵, age=7]
为后面数据库做铺垫