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
classstu{PrivateString name; PrivateString num; Privatecourse[] Course; PublicStu () {} PublicStu (String name,string num) { This. Name =name; This. num =num; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString Getnum () {returnnum; } Public voidsetnum (String num) { This. num =num; } Publiccourse[] GetCourse () {returncourse; } Public voidsetcourse (course[] Course) { This. course =course; } PublicString GetInfo () {return"Name:" +name+ "Study No.:" +num; }}
Defining Course Classes
classcourse{PrivateString name; Privatestu[] Stu; PublicCourse () {} PublicCourse (String name) { This. Name =name; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Publicstu[] Getstu () {returnStu; } Public voidSetstu (stu[] Stu) { This. Stu =Stu; } PublicString GetInfo () {return"Course:" +name; } }
In the Main method test
First, the Stu and course objects are defined, each with three
New Stu ("Zhang San", "001"); New Stu ("John Doe", "002"); New Stu ("Harry", "003"); New Course ("Java"); New Course ("PHP"); New Course ("Python");
Set each other's relationships, each object has multiple objects corresponding to
// setting 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