Many pairs of mappings can be demonstrated with students and courses. One student can choose multiple courses, and one course corresponds to multiple students.
Defining student Classes
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: "+name+": "+num; }}
Defining Course Classes
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 "course :" +name; } }
In the Main method test
First, the Stu and course objects are defined, each with three
Stu S1 = new Stu ("Zhang San", "001"); Stu s2 = new Stu ("John Doe", "002"); Stu s3 = new Stu ("Harry", "003"); Course C1 = new Course ("Java"); Course C2 = new Course ("PHP"); Course C3 = New Course ("Python");
Set each other's relationships, each object has multiple objects corresponding to
Set up the relationship between students and courses S1.setcourse (new course[]{c1,c2}); S2.setcourse (New course[]{c1,c3}); S3.setcourse (New course[]{c2,c3}); The relationship between the corresponding curriculum and the students C1.setstu (new stu[]{s1,s2}); C2.setstu (New Stu[]{s1,s3}); C3.setstu (New STU[]{S2,S3});
Access to course information according to the student
System.out.println (S1.getinfo () + "class selected by students"); for (int i=0; I<s1.getcourse (). length; i++) { System.out.println (S1.getcourse () [I].getinfo ()); }
Run
Access to student information according to the course
System.out.println (C2.getinfo () + "Select Student information for this course"); for (int i=0; I<c2.getstu (). length; i++) { System.out.println (C2.getstu () [I].getinfo ()); }
Run
Many-to-many mapping relationships in Java (go)