〖Java類集〗_範例講解:一對多關聯性筆記
執行個體要求:
使用類集可以表示出以下的關係:一個學校可以包含多個學生,一個學生屬於一個學校,那麼這就是一個典型的一對多的關係,此時就可以通過類集進行關係的表示。
3、本執行個體主要採用的知識
1、類的設計
2、類集
4、具體內容
一個學校有多個學生,那麼學生的個數屬於未知數,那麼這樣一來肯定無法用普通的對象數組表示。所以必須通過類集表示。
代碼:
School.java
import java.util.List;import java.util.ArrayList;public class School{ private String name; private List<Student> allStudents; public School(){ this.allStudents = new ArrayList<Student>(); } public School(String name){ this(); this.setName(name); } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public List<Student> getAllStudents(){ return this.allStudents; } public String toString(){ return "學校名稱:"+this.name; }}
Student.java
public class Student{ private String name ; private int age ; private School school; // 一個學生屬於一個學校 public Student(String name,int age){ this.setName(name) ; this.setAge(age) ; } public void setSchool(School school){ this.school = school ; } public School getSchool(){ return this.school ; } public void setName(String name){ this.name = name ; } public void setAge(int age){ this.age = age ; } public String getName(){ return this.name; } public int getAge(){ return this.age ; } public String toString(){ return "學生姓名:" + this.name + ";年齡:" + this.age ; }};
TestDemo.java
import java.util.Iterator;public class TestDemo{ public static void main(String[] args){ School sch = new School("清華大學"); Student s1 = new Student("張三",21); Student s2 = new Student("李四",22); Student s3 = new Student("王五",23); sch.getAllStudents().add(s1); sch.getAllStudents().add(s2); sch.getAllStudents().add(s3); s1.setSchool(sch); s2.setSchool(sch); s3.setSchool(sch); System.out.print(sch); Iterator<Student> iter = sch.gerAllStudents().iterator(); while(iter.hasNext()){ System.out.println("\t|- "+iter.next()); } }}
5、總結
1、明白類集的關係,那麼這種關係將稱為日後標準程式的開發的基礎。