java:类集操作,多对多的关系
//一个课程有多个学生报名,
//一个学生可以报名多个课程
demo.java, Student.java, Course.java'
public class Course {
private String name;
private int course;
private List<Student> allStudent;
public Course() {
this.allStudent = new ArrayList<Student>();
}
public Course(String name, int course) {
this();
this.name = name;
this.course = course;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCourse() {
return course;
}
public void setCourse(int course) {
this.course = course;
}
public List<Student> getAllStudent() {
return allStudent;
}
public String toString()
{
return "课程:"+this.name +",学分:"+this.course;
}
}
Student.java
public class Student {
private String name;
private int age;
private List<Course> allCourse;
public Student() {
this.allCourse = new ArrayList<Course>();
}
public Student(String name, int age) {
this();
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 List<Course> getAllCourse() {
return allCourse;
}
public String toString()
{
return "学生:"+this.name + ",年龄:"+this.age;
}
}
demo.java
//一个学生可以报名多个课程
Course c1 = new Course("java",5);
Course c2 = new Course("linux",5);
Student st1 = new Student("张三",22);
Student st2 = new Student("李四",33);
Student st3 = new Student("王五",32);
Student st4 = new Student("田七",29);
Student st5 = new Student("赵六",28);
//第一课程
c1.getAllStudent().add(st1);
c1.getAllStudent().add(st3);
st1.getAllCourse().add(c1);
st2.getAllCourse().add(c2);
//第二课程
c2.getAllStudent().add(st1);
c2.getAllStudent().add(st2);
c2.getAllStudent().add(st3);
c2.getAllStudent().add(st4);
c2.getAllStudent().add(st5);
st1.getAllCourse().add(c2);
st2.getAllCourse().add(c2);
st3.getAllCourse().add(c2);
st4.getAllCourse().add(c2);
st5.getAllCourse().add(c2);
//输出
System.out.println(c1);
Iterator<Student> stu = c1.getAllStudent().iterator();
while(stu.hasNext())
{
System.out.println("__" + stu.next());
}
System.out.println(st1);
Iterator<Course> cour = st1.getAllCourse().iterator();
while(cour.hasNext())
{
System.out.println( "__" + cour.next());
}
输出的结果为:
课程:java,学分:5
__学生:张三,年龄:22
__学生:王五,年龄:32
学生:张三,年龄:22
__课程:java,学分:5
__课程:linux,学分:5